Irfan
Irfan

Reputation: 7059

Conditional Order by clause in mysql

I have read some posts having the same problem. I tried to adapt their answers but not succeeded. I want to sort columns by status than as per status further sort the columns. May the below query will clear my point

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')

UPDATE: After below query

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

I've got the below error

#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

If my table name is table than For this recored

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

if current date is 06/21/2012

the output should be

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

May this information is enough. Please let me know if it's not clear yet.

Thanks

Upvotes: 1

Views: 1165

Answers (2)

Devart
Devart

Reputation: 121902

Try this one -

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())
  )

Upvotes: 3

Ronn0
Ronn0

Reputation: 2259

I guess this (new) solution will do the trick:

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'))

Upvotes: 0

Related Questions