MySQL: 如何根据另一个字段的值对某些记录按 ASC 顺序排序,对某些记录按 DESC 顺序排序

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

我有一个 table 的 "tickets"。
Table结构:

  • 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