我需要一个日期时间字段的MySQL条件ORDER BY语句。我有一个包含帖子的表格,我想通过以下方式订购:所有将来的帖子应该订购 ASC 以及所有历史帖子已订购的 DESC 即可。例如:
post_status post_date post_title
=========== ========= ==========
future 2012-10-01 Title 1
future 2012-12-01 Title 2
publish 2012-05-01 Title 3
publish 2012-01-01 Title 4
我需要类似于以下SQL的内容......
SELECT post_status, post_date, post_title FROM wp_posts
WHERE post_status IN ('future', 'publish')
ORDER BY post_status ASC,
CASE post_status
WHEN 'future' THEN 'post_date ASC'
ELSE 'post_date DESC'
END;
有关如何执行此操作的任何提示? 谢谢!
答案 0 :(得分:16)
试试这个:
ORDER BY post_status ASC,
CASE post_status WHEN 'future' THEN POST_DATE END ASC,
CASE WHEN post_status <> 'future' THEN post_date END DESC
答案 1 :(得分:1)
这样的事情怎么样?选择两次并结合结果。
Select * from (SELECT post_status, post_date, post_title
FROM wp_posts WHERE post_status IN ('future')
ORDER BY post_status ASC ) alias1
UNION
Select * from (SELECT post_status, post_date, post_title
FROM wp_posts WHERE post_status IN ('publish')
ORDER BY post_status DESC ) alias2
答案 2 :(得分:1)
试试这个 -
SELECT
post_status, post_date, post_title
FROM
wp_posts
WHERE
post_status IN ('future', 'publish')
ORDER BY
IF(post_status = 'future', 0, 1),
IF(post_status = 'future', TO_DAYS(post_date), TO_DAYS(post_date) * -1);
答案 3 :(得分:0)
我会使用union all
,order by
中的技巧无法使用索引而且速度较慢。
SELECT * FROM
((SELECT
1 AS a, @rownum:=@rownum+1 B, post_status, post_date, post_title
FROM
wp_posts, (SELECT @rownum:=0) r
WHERE
post_status='publish'
ORDER BY
post_date DESC)
UNION ALL
(SELECT
2 AS a, @rownum:=@rownum+1 B, post_status, post_date, post_title
FROM
wp_posts, (SELECT @rownum:=0) r2
WHERE
post_status='future'
ORDER BY
post_date)) ORDER BY A,B;