GROUP_CONCAT change GROUP BY order

后端 未结 3 495

I have a VIEW (lots of joins) that outputs data ordered by a date ASC. Works as expected.

OUTPUT similar to:

ID date         tag         


        
3条回答
  •  囚心锁ツ
    2021-01-18 15:40

    Looks like GROUP_CONCAT no longer preserves the VIEW order. Is this normal?

    Yes, it is normal.

    You should not rely, ever, on the order in which ungrouped and unaggregated fields are returned.

    GROUP_CONCAT has its own ORDER BY clause which the optimizer takes into account and can change the order in which is parses the records.

    To return the first record along with GROUP_CONCAT, use this:

    SELECT  m.*, gc
    FROM    (
            SELECT  id, MIN(date) AS mindate, GROUP_CONCAT(tags) AS gc
            FROM    myview
            GROUP BY
                    id
            ) md
    JOIN    m.*
    ON      m.id = md.id
            AND m.date = md.mindate
    

提交回复
热议问题