GROUP_CONCAT change GROUP BY order

后端 未结 3 492

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:30

    That is because mysql does not guarantee what exact rows will be returned for the fields that are not used in aggregation functions or wasn't used to group by.

    And to be clear "mature" rdbms (such as postgre, sql server, oracle) do not allow to specify * in GROUP BY (or any fields without aggregation or that was not specified in GROUP BY) - and it is great "limitation".

    0 讨论(0)
  • 2021-01-18 15:39

    How about ordering your GROUP_CONCAT?

    SELECT value1, GROUP_CONCAT(value1 ORDER BY date DESC)   
    FROM table1  
    GROUP BY value1;
    

    That's the syntax you need a presume.

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题