简体   繁体   中英

MySQL: how to sort some records in ASC and some in DESC order, based on another field's value

I have a table of "tickets".
Table structure:

  • unique ID (auto-increment)
  • status (open/closed/exception)
  • priority (numeric, larger number = higher priority)
  • creation_date
  • etc...

I need to retrieve the tickets in the following order:

  • "open" tickets first, sorted by priority (highest first), then by creation_date (oldest first)
  • "closed" tickets next, sorted by creation_date (newest first)

This could be done with a UNION of two queries, but this would add a lot of complexity.

Any suggestions for accomplishing this in a single query?

Don't use union all . Use multiple keys in the order by :

select t.*
from t
where status in ('open', 'closed')
order by (status = 'open') desc,
         (case when status = 'open' then priority end) desc,
         (case when status = 'open' then creation_date end) asc,
         (case when status = 'closed' then creation_date end) 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