我有一张“门票”表。
表结构:
- unique ID (auto-increment)
- status (open/closed/exception)
- priority (numeric, larger number = higher priority)
- creation_date
- etc...
我需要按以下顺序取票:
- "open" tickets first, sorted by priority (highest first), then by creation_date (oldest first)
- "closed" tickets next, sorted by creation_date (newest first)
这可以通过两个查询的 UNION 来完成,但这会增加很多复杂性。
对于在单个查询中完成此操作有什么建议吗?
最佳答案
不要使用union all
。在 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
关于MySQL:如何根据另一个字段的值对 ASC 中的一些记录和 DESC 顺序中的一些记录进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47928617/