开发者

Question about MySQL ORDER BY

I have a table called posts where I have two fields called timestamp_added and timestamp_edited.

I want to order by the latest added or edited posts descending.

ORDER BY p.timestamp_added DESC, p.timestamp_edited DESC, does not give me what I need.

I would love something like:

ORDER BY IF p.timesta开发者_开发百科mp_edited > 0 THEN p.timestamp_edited DESC ELSE p.timestamp_added DESC

How do I do this? I have tried to google this, but I have trouble finding what I need.


Is the timestamp_edited NULL when not set?

In that case you could do:

ORDER BY IFNULL(p.timestamp_edited, p.timestamp_added) DESC 

If it's 0 when not set:

ORDER BY IF(p.timestamp_edited > 0, p.timestamp_edited, p.timestamp_added) DESC


Your version was close. This should do what you need and is standard SQL

ORDER BY 
   CASE WHEN p.timestamp_edited > 0 
        THEN p.timestamp_edited 
        ELSE p.timestamp_added 
   END DESC


AS N.B. suggested, your timestamp_edited should be same as timestamp_added at the time of creation and then simply use ORDER BY timestamp_edited DESC


In case you store p.timestamp_edited as 00-00-00T00:00:00 by default You could try ORDER BY GREATEST(p.timestamp_edited, p.timestamp_added) DESC

Update
This Case also handles null and I checked it on a database and works perfectly

ORDER BY GREATEST(p.timestamp_added, IFNULL(p.timestamp_edited, 0)) DESC

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜