简体   繁体   中英

Mysql sort order date 0000-00-00 first

The below MySQL query works, but not the way I like.

Some posts have a date of 0000-00-00 . How can I list those first and then the rest.

SELECT *
FROM posts
ORDER BY posts.created DESC

Example results

0000-00-00 - A post
0000-00-00 - Another post
2019-02-03 - New post
2011-01-01 - Old post

One method is to add an explicit key:

SELECT p.*
FROM posts p
ORDER BY (p.created = '0000-00-00') DESC,
         p.created DESC

Try:

CREATE VIEW test1 AS SELECT p.* FROM posts p WHERE p.created = '0000-00-00';

CREATE VIEW test2 AS SELECT p.* FROM posts p WHERE p.created <> '0000-00-00' ORDER BY p.created DESC;

CREATE VIEW t_final AS ( SELECT * FROM test1 UNION ALL SELECT * FROM test2 )

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