[英]Order by Date in MySQL & PHP and giving importance to today date
I want to make an order by date to get the comments of user, but I want to give the importance to today date 我想按日期排序以获取用户的评论,但我想强调今天的日期
if there's a comment today show it first and make the ordering with date for the rest. 如果今天有评论,请先显示,然后按日期进行订购。
I try to make this but always give me an error in syntax 我试图做到这一点,但总是在语法上给我一个错误
SELECT *
FROM comment
ORDER BY IF(`DATE_TIME_COMMENT` = CURRENT_DATE())
is there any solution ? 有什么解决办法吗?
If you can't have comments with future date, just order by date 如果您对未来的日期没有意见,只需按日期排序
SELECT * FROM comment ORDER BY DATE_TIME_COMMENT DESC
If you can have future date, and want to order first the today date, then comments with other date than today, one way to do this is with a UNION
如果您可以确定将来的日期,并想先订购今天的日期,然后再用除今天以外的其他日期进行注释,那么一种方法是使用UNION
SELECT * FROM (
SELECT 1 as order, c.* FROM comment c WHERE DATE_TIME_COMMENT = CURRENT_DATE()
UNION ALL
SELECT 2 as order, c.* FROM comment c WHERE DATE_TIME_COMMENT <> CURRENT_DATE()
) order by order asc, DATE_TIME_COMMENT desc
That you get first the today comments, then other comments order by date 首先得到今天的评论,然后按日期排序其他评论
First sort by a CASE
returning "something lower", if date_time_comment
is equal to current_date()
and "something higher" else. 如果date_time_comment
等于current_date()
,则首先返回CASE
返回“更低的东西”,否则返回“更高的东西”。 Then, second, sort by date_time_comment
. 然后,第二,按date_time_comment
排序。
SELECT *
FROM comment
ORDER BY CASE date_time_comment
WHEN current_date()
THEN 0
ELSE
1
END,
date_time_comment;
(Possibly add DESC
after date_time_comment
in the ORDER BY
clause, if you want to have newest comments first.) (如果您想首先拥有最新的注释,则可以在ORDER BY
子句中的date_time_comment
之后添加DESC
。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.