1

我读过一些有同样问题的帖子。我试图调整他们的答案,但没有成功。我想按状态对列进行排序,而不是按状态对列进行进一步排序。可能以下查询将清除我的观点

SELECT a.*,STR_TO_DATE(d_date, "%m/%d/%Y")>CURDATE() as status
FROM table AS a ORDER BY status DESC, 
IF(status=0,
'DATEDIFF(STR_TO_DATE( a.d_date, "%m/%d/%Y" ),CURDATE()) DESC',
'DATEDIFF(STR_TO_DATE( a.d_date, "%m/%d/%Y" ),CURDATE()) ASC')

更新:经过以下查询

SELECT a . * , STR_TO_DATE( d_date,  "%m/%d/%Y" ) > CURDATE( ) AS 
STATUS 
FROM  `table` AS a
ORDER BY STATUS DESC , IF( 
STATUS =0, DATEDIFF( STR_TO_DATE( a.d_date,  "%m/%d/%Y" ) , CURDATE( ) ) DESC , DATEDIFF( STR_TO_DATE( a.d_date, "%m/%d/%Y" ) , CURDATE( ) ) ASC ) 
LIMIT 0 , 30

我有以下错误

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DESC, DATEDIFF(STR_TO_DATE( a.d_date, "%m/%d/%Y" ),CURDATE()) ASC) LIMIT ' at line 4

如果我的表名table比这个记录

d_date
06/28/2012
06/23/2012
06/20/2012
06/19/2012

如果当前日期是06/21/2012

输出应该是

d_date               status
06/23/2012              1
06/28/2012              1
06/20/2012              0
06/19/2012              0

可能这些信息就足够了。如果还不清楚,请告诉我。

谢谢

4

2 回答 2

3

试试这个——

SELECT
  a.*,
  STR_TO_DATE(d_date, '%m/%d/%Y') > CURDATE() AS status
FROM
  table AS a
ORDER BY
  status DESC, 
  IF(status = 0,
    DATEDIFF(STR_TO_DATE(a.d_date, '%m/%d/%Y'),CURDATE()) * -1,
    DATEDIFF(STR_TO_DATE(a.d_date, '%m/%d/%Y'),CURDATE())
  )
于 2012-06-21T12:03:18.317 回答
0

我想这个(新的)解决方案可以解决问题:

SELECT a.*, STR_TO_DATE(d_date, "%m/%d/%Y")>CURDATE() as status 
FROM `table` AS a ORDER BY status DESC, 
IF(status=0,
CONCAT_WS(' ', DATEDIFF(STR_TO_DATE( a.d_date, "%m/%d/%Y" ),CURDATE()), 'DESC'),
CONCAT_WS(' ', DATEDIFF(STR_TO_DATE( a.d_date, "%m/%d/%Y" ),CURDATE()), 'ASC'))
于 2012-06-21T11:31:22.947 回答