简体   繁体   English

MySQL按多列组合排序(不按order1 asc,field2 asc排序)

[英]MySQL Order by multiple column combined (not order by field1 asc, field2 asc)

it seems like a typical question but it's different. 这似乎是一个典型的问题,但它有所不同。

I have a table with an id and 3 timestamp fields (to simply). 我有一个带有id和3个时间戳字段的表(简单地说)。 Initially all 3 fields are null, and they get filled with values. 最初所有3个字段都为空,并且它们填充了值。 Examples of rows are: 行的示例是:

id time1      time2      time3
1  1259625661 1259643563 null
2   null      1259621231 null
3  1259625889 null       1259644511
4   null      1259621231 null
5   null      null       1259644511
6   null      1259621231 null
7  1259625889 null       null

What I need is to get a list of the id's sorted by the most recent timestamp (ignoring if it's in time1, time2 or time3). 我需要的是获取按最新时间戳排序的id列表(忽略它是在t​​ime1,time2还是time3)。 Doing a order by time1 desc, time2 desc, time3 desc gives me a wrong list, as it first sorts all the time1 field, then the second, etc... 通过time1 desc,time2 desc,time3 desc执行一个命令给了我一个错误的列表,因为它首先排序所有time1字段,然后是第二个,等等...

Expected result is a list of id's. 预期结果是id的列表。

That can be done in MySQL in a single query? 那可以在一个查询中在MySQL中完成吗? Thanks 谢谢

SELECT  *
FROM    mytable
ORDER BY
        GREATEST(
        COALESCE(time1, 0),
        COALESCE(time2, 0),
        COALESCE(time3, 0)
        ) DESC

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

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