I’m dealing with two tables in MySQL and facing issues with an UPDATE command that involves a JOIN.
The Employee table comprises the following columns:
EmpId(primary key)EmpNameEmpDeptId(foreign key)
Meanwhile, the Departments table includes:
DeptId(primary key)DeptName
The Departments table has two entries: DeptId 1 representing “Marketing” and DeptId 2 for “Sales”.
There’s an employee named Bob, who is in Marketing (DeptId = 1). I want to change his department to Sales, but I only have the department name “Sales” and not the ID 2.
The following straightforward update works without issues:
UPDATE Employee
SET EmpDeptId = 2
WHERE EmpName = 'Bob'
However, I need to perform this operation using the department name instead of its ID. I attempted this query but it hasn’t succeeded:
UPDATE Employee AS E
INNER JOIN Departments AS D ON D.DeptId = E.EmpDeptId
SET E.EmpDeptId = D.DeptId
WHERE D.DeptName = 'Sales' AND E.EmpName = 'Bob'
I’ve experimented with various methods using aliases and different JOIN configurations, but nothing appears to be right. Can anyone help me understand what the problem might be?