Question

Screenshot

Here I have some data. I want to show the records which have fav=1 at fast, then I want to show the data where the date is greater than the current date in ascending order(date) and at last the remaining records in descending order(date). I have written a query, but it is not working as expected:

(SELECT * 
FROM `test` 
WHERE fav = 1 
ORDER BY date DESC) 

UNION 

(SELECT * 
FROM `test` 
WHERE fav = 0 
    AND date>DATE(NOW()) 
ORDER BY date ASC) 

UNION 

(SELECT * 
FROM `test` 
WHERE fav = 0 
    AND date>=DATE(NOW()) 
ORDER BY date DESC)

Please share the query if you know how to do it. Thank you.

Was it helpful?

Solution

I want to show the records which have fav=1 at fast, then I want to show the data where the date is greater than the current date in ascending order(date) and at last the remaining records in descending order(date).

Try:

SELECT * 
FROM `test`
ORDER BY fav=1 desc,
         fav=0 AND `date`>=DATE(NOW()) DESC,
         CASE WHEN fav=0 AND `date`>=DATE(NOW()) 
                  THEN UNIX_TIMESTAMP(`date`)
                  ELSE -UNIX_TIMESTAMP(`date`)
              END ASC;
Licensed under: CC-BY-SA with attribution
Not affiliated with dba.stackexchange
scroll top