我正面临这种情况:表Employee有join_date列。表预订具有booking_date列和Employee的外键(employee_id)。 Employee在join_date列中有一些NULL值。我想填写这些员工的FIRST booking_date值。我该怎么办?
供参考: 我可以使用复杂的连接语句进行查询,以提取join_date为NULL的员工的第一个booking_date,如下所示:
SELECT emp.employee_id, emp.joining_date, temp2.booking_date FROM employee emp
LEFT JOIN (SELECT bo.employee_id, bo.booking_date FROM booking bo
INNER JOIN (SELECT employee_id, MIN(booking_date) mindate FROM booking GROUP BY employee_id) temp1
ON bo.employee_id = temp1.employee_id AND bo.booking_date = temp1.mindate) temp2
ON emp.employee_id = temp2.employee_id
WHERE emp.joining_date IS NULL;
但我正在努力将这个复杂的选择放入更新语句中:
UPDATE employee emp
SET emp.joining_date = (SELECT ...)
WHERE emp.joining_date IS NULL;
答案 0 :(得分:0)
你的select语句比它需要的更复杂,你将以这种方式获得相同的设置:
SELECT emp.employee_id,min(bo.booking_date) booking_date
FROM employee emp
LEFT JOIN booking bo
ON bo.employee_id = emp.employee_id
WHERE emp.joining_date is NULL
GROUP BY emp.employee_id;
您的更新可以像这样完成,请注意"并且存在" section是可选的,但我倾向于包含它以使查询的意图更清晰。
UPDATE employee emp
SET emp.joining_date =
(SELECT min(booking_date) from booking bo where bo.employee_id = emp.employee_id)
WHERE emp.joining_date IS NULL
and exists(select * from booking bo where bo.employee_id = emp.employee_id);