简体   繁体   中英

Order by multiple columns with multiple conditions

I have a table with some events like this

id----------title-----------date-------------status
1-----------birthday-------2018-03-12--------1
2-----------match----------2018-03-13--------2
3-----------anniversary----2018-03-10--------1
4-----------trip-----------2018-03-15--------1
5-----------birthday-------2018-03-17--------2
6-----------birthday-------2018-03-11--------1

Expected Result

id----------title-----------date-------------status
1-----------birthday-------2018-03-12--------1
4-----------trip-----------2018-03-15--------1
5-----------birthday-------2018-03-17--------2
2-----------match----------2018-03-13--------2
6-----------birthday-------2018-03-11--------1
3-----------anniversary----2018-03-10--------1

I need to query it like the first rows which have dates greater than today with status 1 should appear first and then the rest in desc.

Suppose today is 2018-03-11 then row with id 1 should appear first and then the rest of the rows is desc order

This is what I have tried so far

SELECT *
FROM events
ORDER BY (date > CURDATE() and status = 1) asc,
         date desc

You can use multiple keys in an order by :

order by (date >= curdate() and status = 1) desc,
         date desc

I believe your SQL should be something like this but is hard to say without expected results.

Query

SELECT 
 *
FROM 
 [table]
WHERE 
  date > CURDATE()
AND
  status = 1
ORDER BY 
  date ASC
LIMIT 1

UNION 

SELECT 
 *
FROM 
 [table]
WHERE 
   id NOT IN (
    SELECT 
      id
    FROM 
     [table]
    WHERE 
       date > CURDATE()
    AND
       status = 1
    LIMIT 1
   )
 AND
   date > CURDATE()
ORDER BY 
 date DESC

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM