简体   繁体   中英

How to order SQL result with date > NOW() ASC and the rest DESC?

I've got a WordPress database with a custom post type called events with custom fields for startdates and enddates of the events. I would like to output all of those events in a list having the upcoming events listed first in an ascending order and the rest listed in a descending order.

I tried to copy the code from this answer but i can't seem to get it right – all the posts are sorted ascendingly: MySQL conditional ORDER BY ASC/DESC for date column

This is my code right now:

SELECT p.post_title, m.meta_value 
FROM wp_posts as p, wp_postmeta as m 
WHERE p.ID = m.post_id 
    AND p.post_type = "events"
    AND m.meta_key = "startdate" 
    AND p.post_status = "publish"
ORDER BY m.meta_value ASC,
    CASE m.meta_value WHEN m.meta_value > DATE(NOW()) THEN m.meta_value END ASC,
    CASE WHEN m.meta_value < DATE(NOW()) THEN m.meta_value END DESC
LIMIT 10

Remove the first clause in the order by . It should read:

ORDER BY 
    CASE m.meta_value WHEN m.meta_value > DATE(NOW()) THEN m.meta_value END ASC,
    CASE WHEN m.meta_value < DATE(NOW()) THEN m.meta_value END DESC

Actually, I'm not sure what the collating sequence of NULLs are in postgres. You can get what you want by doing:

ORDER BY 
    CASE m.meta_value WHEN m.meta_value > DATE(NOW()) THEN m.meta_value
                      else cast('9999-01-01' as date) END ASC,
    CASE WHEN m.meta_value < DATE(NOW()) THEN m.meta_value END DESC

I think this will do it. The logic is sound, but I'm not that familiar with mysql and so you may need to do a conversion or two in the 2nd case:

ORDER BY CASE WHEN m.meta_value > DATE(NOW()) THEN 0 ELSE 1 END,
         CASE WEHN m.meta_value > DATE(NOW()) THEN m.meta_value ELSE m.meta_value * -1 END

The trick is that you want to treat dates as a number, and mysql may require you to do this a little differently. It works because within that second level the sort only applies when the values from the first level are equal: so all upcoming events will be sorted to the top, and within those upcoming events there are sorted ascending. All past events will show next, and within that list they will sort descending, because we inverted the date value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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