可能重复:
Fetch the row which has the Max value for a column如何获取每个分组的最新行数?
我的表如下所示:
Sales
- id
- country_id
- location_id
- order_id
- created
现在我想返回只有一行(最新的,它可以使用最高的id值或使用创建的日期时间字段)为每个country_id,location_id对。
这是可能在一个单一的查询?
可能重复:
Fetch the row which has the Max value for a column如何获取每个分组的最新行数?
我的表如下所示:
Sales
- id
- country_id
- location_id
- order_id
- created
现在我想返回只有一行(最新的,它可以使用最高的id值或使用创建的日期时间字段)为每个country_id,location_id对。
这是可能在一个单一的查询?
select * from (
select * from mytable
order by id desc) x
group by country_id, location_id;
这是一个只有MySQL的解决方案,但它的作品,因为当你不聚集孟群按列,MySQL允许你第一它会为每个组找到它,如果您在分组之前对这些行进行排序,则会得到您想要的拖曳。
这应该只是
select country_id, location_id, max(created)
from sales
group by country_id, location_id
-1您的查询查找每个组合的最大ID,但他希望*整行*的最大ID为 – Bohemian
事实上 - 这不是'country_id'和'location_id'需要来自同一行的情况'最大(创建)'!一个常见的误解。 ([“服务器可以自由选择每个组中的任何值,因此除非它们相同,否则所选值是不确定的。”](http://dev.mysql.com/doc/refman/5.0/en/group -by-extensions.html)) –
嗯,大声笑。我没有发现你也在这些领域分组。傻我... –
不会“GROUP BY'按字段分组排序,所以'1 by desc'变得毫无用处? – meze
@meze不是无用的。它确保每个组合所遇到的第一行是你想要的。请参阅已编辑的答案以获得更多解释 – Bohemian
对,更糟糕的是,因为不能保证它总会返回组的第一行。 – meze