简体   繁体   English

MySQL:如何根据另一个字段的值对ASC中的某些记录和DESC顺序中的某些记录进行排序

[英]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) 唯一ID(自动递增)
  • 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) 首先“打开”票证,按优先级(最高)排序,然后按creation_date(最早的)排序
  • "closed" tickets next, sorted by creation_date (newest first) 接下来是“关闭”的票证,按creation_date(最新的)排序

This could be done with a UNION of two queries, but this would add a lot of complexity. 可以通过两个查询的UNION来完成,但这会增加很多复杂性。

Any suggestions for accomplishing this in a single query? 有任何建议在单个查询中完成此操作吗?

Don't use union all . 不要union all使用union all Use multiple keys in the order by : 按以下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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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