MySQL按多个字段排序

时间:2017-04-03 15:48:16

标签: mysql

在MySQL中,我有这个表:

id   updateTime  writeTime 
------------------------------
1     null       2017-04-05 
2     null       2017-04-01 
3    2017-04-02  2017-04-02
4    2017-04-02  2017-03-31

我想要这个结果:

id   updateTime  writeTime 
------------------------------
1     null       2017-04-05 
3    2017-04-02  2017-04-02
4    2017-04-02  2017-03-31
2     null       2017-04-01  `

但是当我使用ORDER BY updateTime, writeTime DESC时,我通常会得到:

id   updateTime  writeTime 
------------------------------
3    2017-04-02  2017-04-02
4    2017-04-02  2017-03-31
1     null       2017-04-05 
2     null       2017-04-01  `

2 个答案:

答案 0 :(得分:1)

如果我理解正确,您希望按updateTime排序。如果该值为null,则按Writetime排序。如果updateTime相等,则按writeTime排序。

您可以使用coalesce:

select *
from your_table
order by coalesce(updateTime, writeTime) desc, writeTime desc;

答案 1 :(得分:0)

我想你想在最大的日期订购:

select 
   *
from your_table
order by coalesce(GREATEST(updateTime, writeTime),updateTime, writeTime) desc;