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

标签 mysql sql sorting sql-order-by

我有一张“门票”表。
表结构:

  • 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/

相关文章:

php - 如何根据数组中指定的字母表以最少的时间损失对大型数组进行排序?

php - 在 SQL 中,我如何获得每个玩家的奖励总数

python - 如何像使用 Python 一样使用 SQL,通过复制行同时更改该行中的一个值(其中该值源自不同的列)?

mysql - Redis 排序 : How do I sort a redis hash key by given value?

mysql - 成对索引和单列索引的区别?

SQL 服务器 : slow query with 3 "OR" condition and order by Id

python - 使用复合返回语句对字典和列表的字典进行排序

java - 根据属性对 Map 进行排序

php - 日期范围查询 MySQL

mysql外键引用同一个表字段