GROUP BY return the first record

前端 未结 2 1855
长情又很酷
长情又很酷 2021-01-04 11:47

As far as I know mysql GROUP BY groups to the last record found.

Is there any solution to GROUP BY the first record?

I have setup the ORDER in SQL command an

相关标签:
2条回答
  • 2021-01-04 12:15

    Add LIMIT 1 to your query.

    0 讨论(0)
  • 2021-01-04 12:16

    I assume you are talking of something like

    SELECT  *
    FROM    mytable
    GROUP BY
            column
    

    You shouldn't use unaggregated expressions in GROUP BY unless they are all same within the group.

    If you want to return the record holding the least value of an expression within a group, use this:

    SELECT  mo.*
    FROM    (
            SELECT  DISTINCT column
            FROM    mytable
            ) md
    JOIN    mytable mo
    ON      mo.id = 
            (
            SELECT  id
            FROM    mytable mi
            WHERE   mi.column = md.column
            ORDER BY
                    mi.column, mi.someorder
            LIMIT 1
            )
    
    0 讨论(0)
提交回复
热议问题