我有这样的查询:
SELECT id, id_employee, hours FROM WorkHours WHERE hours > 8;
如何为该查询选择的每个工作记录选择以前的工作记录?
因此,对于这样的表(id,id_employee,小时):
1 - 1 - 5
2 - 2 - 3
3 - 1 - 9
4 - 1 - 4
5 - 2 - 4
6 - 2 - 10
7 - 2 - 7
8 - 1 - 7
9 - 2 - 9
记录3、6和9将被选择。我也要获取记录1、5、7。基本上,每次有人加班时,我想看看这个人在以前记录的一天有多少小时。
最佳答案
您可以使用相关的子查询获取前一个id
:
SELECT wh.id, wh.id_employee, wh.hours,
(SELECT MAX(wh2.id)
FROM WorkHours wh2
WHERE wh2.id_employee = wh.id_employee AND wh2.id < wh.id
) as prev_id
FROM WorkHours wh
WHERE wh.hours > 8;
然后,要获取完整的行,请使用
JOIN
:SELECT eh.*, wh.*
FROM (SELECT wh.id, wh.id_employee, wh.hours,
(SELECT MAX(wh2.id)
FROM WorkHours wh2
WHERE wh2.id_employee = wh.id_employee AND wh2.id < wh.id
) as prev_id
FROM WorkHours wh
WHERE wh.hours > 8
) eh LEFT JOIN
WorkHours wh
ON wh.id_employee = eh.id_employee;