简体   繁体   English

MySQL - 按DESC的顺序分组

[英]MySQL - Group by with Order by DESC

table: uuid, version, datetime 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 版本不是唯一的,但想法是仅获取给定uuid的最新日期时间的行

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

... of course gets datetime asc results -- is there a way to "preorder" the group by to desc, so that only the latest version is fetched? ...当然获取datetime asc结果 - 有没有办法将该组“预先排序”到desc,以便只获取最新版本?

since the table only has those 3 field, and you are filtering by uid you can just use the MAX without the JOIN: 由于该表只有那3个字段,并且您通过uid进行过滤,因此您只需使用不带JOIN的MAX:

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: 但是,如果表有更多字段,或者您没有按uid过滤 - 您需要先为每个版本获取MAX日期时间,然后选择行:

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
SELECT * FROM 
(SELECT * FROM table WHERE uuid='bla' ORDER BY datetime desc) table 
GROUP BY version;

There is a better way for me, you could add a desc to group by: 对我来说有一个更好的方法,你可以通过以下方式添加一个desc

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

why it works is because my id's are generated and so always the latest id means the latest datetime 它的工作原理是因为我的id是生成的,因此最新的id意味着最新的日期时间

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM