1st Row in Group By vs. Last Row

后端 未结 5 777
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-21 10:23

Wondering how to return the 1st row in a MySQL group by vs. the last row. Returning a series of dates, but need the first one displayed.

select * from calendar w         


        
5条回答
  •  滥情空心
    2021-01-21 11:15

    When you use GROUP BY like that, MySQL makes no guarantees about which row in each group you get. Indeed, theoretically it could even pick some of the columns from one row and some from another. The MySQL Reference Manual says:

    "MySQL extends the use of GROUP BY so that the select list can refer to nonaggregated columns not named in the GROUP BY clause. [...] You can use this feature to get better performance by avoiding unnecessary column sorting and grouping. However, this is useful primarily when all values in each nonaggregated column not named in the GROUP BY are the same for each group. The server is free to choose any value from each group, so unless they are the same, the values chosen are indeterminate."

    What you want to do instead is something like this:

    SELECT
      calendar.*
    FROM
      calendar
      NATURAL JOIN (
        SELECT
          eventid, MIN(date) AS date
        FROM
          calendar
        GROUP BY eventid
      ) AS foo
    

提交回复
热议问题