0

In MySQL, I have this table:

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

I want this result:

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  `

But when I use ORDER BY updateTime, writeTime DESC, I usually get:

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
  • 1
    What is the sorting logic of the desired result? Commented Apr 3, 2017 at 15:49
  • I would copy the value of writeTime into updateTime for rows that have not been updated. This way you can order by updateTime using an index. Commented Apr 3, 2017 at 16:21

2 Answers 2

1

If I understand it right, you want to sort by updateTime. If that's null, sort by Writetime. In case of equal updateTime, sort by writeTime.

You can use coalesce for this:

select *
from your_table
order by coalesce(updateTime, writeTime) desc, writeTime desc;
Sign up to request clarification or add additional context in comments.

Comments

0

I think you want to order by the greatest date :

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.