使用 group by in 并返回行的标识
对于这张表...
id type food price
--------------------------
1 veg carrot 10
2 veg turnip 11
3 fruit bramble 6
4 fruit rasp 4
5 fruit current 9
...
我可以像这样返回每种食物类型最昂贵食物的最高价格...
select max(price) from tableName group by type;
但是我想返回包含每种食物类型最昂贵食物的每一行的 id 号。每种食物类型只返回一行。即返回这个......
id
----
2
5
...
这是我真正问题的简化版本。
For this table...
id type food price
--------------------------
1 veg carrot 10
2 veg turnip 11
3 fruit bramble 6
4 fruit rasp 4
5 fruit current 9
...
I can return the max price of the most expensive food for each food type like this...
select max(price) from tableName group by type;
But I'd like to return the id number of each row that contains the most expensive food for each food type. And return one and only one row per food type. Ie return this....
id
----
2
5
...
This is a simplified version of my real problem.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当更多食物具有相同类型和价格时,这个可怕的查询将起作用。
我几乎不会在生产中使用它,因为这是无法维护的。
This horrible query will work when more food have the same type and price.
I would hardly ever use this in production as this is unmaintainable.