How to order or choose rows in MySQL GROUP BY clause?

Deadly 提交于 2019-12-11 03:59:18

问题


I have a table like this:

id       number    otherfields
-------------------------------------------
664      48       aaa
665      49       bbb
666      55       ccc
667      48       ddd

My query groups by the number field, and I want it to pick the first (lowest) id, so that the data comes out like ccc,aaa,bbb (when ordered by number). However I'm getting ccc,ddd,bbb - in other words, it's picking row #667 instead of #664 for the number 48.

Oddly, this only happens on the live server; on localhost I get it the correct way even though the table is exactly the same (exported from localhost, imported onto server).

Is it possible to ensure that the GROUP BY clause picks the first ID?


回答1:


No, it is not possible in MySQL. You have to use a join.

SELECT id, number, otherfields FROM table 
  WHERE id in (SELECT min(id) FROM table GROUP BY number)



回答2:


SQL-92 version.

SELECT 
     id, number, otherfields 
FROM 
     table t
     join (SELECT min(id) as id, number FROM table GROUP BY number) sq --subquery
       on t.id = sq.id


来源:https://stackoverflow.com/questions/3938918/how-to-order-or-choose-rows-in-mysql-group-by-clause

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!