mysql中的条件Order by子句

时间:2012-06-21 11:28:09

标签: mysql

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

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

愿这些信息足够。如果还不清楚,请告诉我。

由于

2 个答案:

答案 0 :(得分: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())
  )

答案 1 :(得分: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'))