如何限制每个用户 ID 一行
How to limit one row per user id
我有这个 table 叫做员工时间表:
empsheet_id|employee_id|timesheet_status|last_update
table 允许经理访问所有员工的时间表。一名员工可以有多个时间表。我想 仅 显示每位员工的最新条目。我读到 in the manual 我必须编写一个分组最大子查询和 left join
与 inner join
但我不确定如何在这里进行。
到目前为止,这是我的查询:
$sqlempsheets="SELECT * FROM employeetimesheets JOIN employees ON employeetimesheets.employee_id=employees.employee_id WHERE employeetimesheets.timesheet_status='Pending Approval'";
$resultempsheets=mysqli_query($db,$sqlempsheets);
试试这个:
select *
from employeetimesheets t
join (
select employee_id,
max(empsheet_id) as empsheet_id
from employeetimesheets
group by employee_id
) t2 on t.employee_id = t2.employee_id
and t.empsheet_id = t2.empsheet_id
join employees e on t.employee_id = e.employee_id
where t.timesheet_status = 'Pending Approval';
或使用left join
:
select t.*, e.*
from employeetimesheets t
left join employeetimesheets t2 on t.employee_id = t2.employee_id
and t.empsheet_id < t2.empsheet_id
join employees e on t.employee_id = e.employee_id
where t.timesheet_status = 'Pending Approval'
and t2.employee_id is null;
我有这个 table 叫做员工时间表:
empsheet_id|employee_id|timesheet_status|last_update
table 允许经理访问所有员工的时间表。一名员工可以有多个时间表。我想 仅 显示每位员工的最新条目。我读到 in the manual 我必须编写一个分组最大子查询和 left join
与 inner join
但我不确定如何在这里进行。
到目前为止,这是我的查询:
$sqlempsheets="SELECT * FROM employeetimesheets JOIN employees ON employeetimesheets.employee_id=employees.employee_id WHERE employeetimesheets.timesheet_status='Pending Approval'";
$resultempsheets=mysqli_query($db,$sqlempsheets);
试试这个:
select *
from employeetimesheets t
join (
select employee_id,
max(empsheet_id) as empsheet_id
from employeetimesheets
group by employee_id
) t2 on t.employee_id = t2.employee_id
and t.empsheet_id = t2.empsheet_id
join employees e on t.employee_id = e.employee_id
where t.timesheet_status = 'Pending Approval';
或使用left join
:
select t.*, e.*
from employeetimesheets t
left join employeetimesheets t2 on t.employee_id = t2.employee_id
and t.empsheet_id < t2.empsheet_id
join employees e on t.employee_id = e.employee_id
where t.timesheet_status = 'Pending Approval'
and t2.employee_id is null;