MySQL - Group by with Order by DESC

后端 未结 3 1409
礼貌的吻别
礼貌的吻别 2020-12-17 02:33

table: uuid, version, datetime

version is not unique, but the idea is to fetch only the rows with the latest datetime for a given uuid

SELECT * FROM ta

相关标签:
3条回答
  • 2020-12-17 03:07

    There is a better way for me, you could add a desc to group by:

    SELECT * FROM table WHERE uuid='bla' GROUP BY version desc

    why it works is because my id's are generated and so always the latest id means the latest datetime

    0 讨论(0)
  • 2020-12-17 03:09

    since the table only has those 3 field, and you are filtering by uid you can just use the MAX without the JOIN:

    SELECT version, MAX(datetime) Maxdatetime
    FROM table
    WHERE uuid='bla'
    GROUP BY version
    

    However, if the table had more fields, or you are not filtering by uid - you need to first get the MAX datetime for each version, then select the row:

    SELECT t.uuid, t.version, t.datetime 
    FROM table t JOIN (
        SELECT version, MAX(datetime) Maxdatetime
        FROM table
        WHERE uuid='bla'
        GROUP BY version
    ) r ON t.version = r.version AND t.datetime = r.Maxdatetime
    WHERE t.uuid='bla'
    ORDER BY t.datetime desc
    
    0 讨论(0)
  • 2020-12-17 03:13
    SELECT * FROM 
    (SELECT * FROM table WHERE uuid='bla' ORDER BY datetime desc) table 
    GROUP BY version;
    
    0 讨论(0)
提交回复
热议问题