mysql命令由两个unixtime列组合而成

时间:2016-06-13 09:37:01

标签: mysql sql-order-by

user结构:

id(PK)(int)
name(varchar)
time1(int10) unixtime
time2(int10) unixtime

SELECT * FROM `user` ORDER BY `time1` DESC,`time2` DESC


 +------------------------------------------------------+
 | id        | name   |     time1     |     time2       |
 +------------------------------------------------------+
 | 12345     | Joe    |  1405605785   |   1406733506    |
 | 12346     | John   |  1406733506   |                 |
 | 12347     | David  |               |   1405684190    |
 +------------------------------------------------------+

我正在使用这个sql:

SELECT * FROM `user` ORDER BY `time1` DESC,`time2` DESC

如何组合两列时间来排序desc?

============

sagi的更多示例回复

 +------------------------------------------------------+
 | id        | name   |     time1     |     time2       |
 +------------------------------------------------------+
 | 12345     | Joe    |  1            |   2             |
 | 12346     | John   |  5            |                 |
 | 12347     | David  |               |   4             |
 +------------------------------------------------------+

我想这样排序(DESC)

John (time = 5)
David (time = 4)
Joe (time  max value = 2)

1 个答案:

答案 0 :(得分:1)

这称为使用CASE EXPRESSION的条件排序:

SELECT * FROM `user` t
ORDER BY CASE WHEN t.time1 is null THEN t.time2 ELSE t.time1 END DESC

也可以写成:

ORDER BY coalesce(t.time1,t.time2)

您没有提供任何预期的结果,如果time1,time2都不是NULL,您没有说明应该在哪个列中订购结果,所以我假设您希望它由第一列订购。如果情况并非如此,请将time1替换为time2

试试这个:

ORDER BY GREATEST(t.time1,t.time2) DESC