我尝试为每个WorkOrder
选择最新的Customer
。我已使用ORDER BY
和GROUP BY
,但返回的结果不是最新的WorkOrder
。
表格结构:
WorkOrder
id
customer_id
create_date
...
示例数据:
WorkOrder.id WorkOrder.customer_id WorkOrder.create_date ...
1 1 2012-01-01 12:00:00
2 1 2016-06-29 12:00:00
3 2 2015-05-05 12:00:00
期望的结果:
WorkOrder.id WorkOrder.customer_id WorkOrder.create_date ...
2 1 2016-06-29 12:00:00
3 2 2015-05-05 12:00:00
当前代码:
$query = DB::table('WorkOrder')
->orderBy('WorkOrder.create_date', 'desc')
->groupBy('WorkOrder.customer_id');
// select * from `WorkOrder` group by `WorkOrder`.`customer_id` order by `WorkOrder`.`create_date` desc
当前结果:
WorkOrder.id WorkOrder.customer_id WorkOrder.create_date ...
1 1 2012-01-01 12:00:00
3 2 2015-05-05 12:00:00
答案 0 :(得分:2)
使用最大功能
SELECT WorkOrder.id, WorkOrder.customer_id, MAX(WorkOrder.create_date) FROM `WorkOrder` GROUP BY `WorkOrder`.`customer_id` ORDER BY `WorkOrder`.`create_date` DESC
答案 1 :(得分:1)
试试这个:
SELECT * FROM WorkOrder
WHERE (customer_id, create_date) IN
(SELECT customer_id, MAX(create_date) FROM WorkOrder
GROUP By customer_id)
ORDER BY ...
答案 2 :(得分:1)
我倾向于使用相关子查询来执行此操作:
select wo.*
from workorder wo
where create_date = (select max(wo2.create_date)
from workorder wo2
where wo2.customer_id = wo.customer_id
);
这种方法优于在子查询中使用group by
:
where
子句中有其他过滤器,则只会在减少的行集上查找值。