我的表格如下:
Sales
- id
- country_id
- location_id
- order_id
- created
现在我只希望为每个country_id,location_id对返回一行(最新的,可以使用最高的id值或使用创建的datetime字段)。
这可以在一个查询中实现吗?
答案 0 :(得分:1)
select * from (
select * from mytable
order by id desc) x
group by country_id, location_id;
这是一个仅限mysql的解决方案,但是它可以正常工作,因为当你没有聚合mon-group-by列时,mysql会为你提供它为每个组找到的第一个行,以及如果你在分组之前订购行,你可以得到你想要的那些。
答案 1 :(得分:-1)
这应该只是
select country_id, location_id, max(created)
from sales
group by country_id, location_id