MySQL: 先按具体项目排序再按时间排序
MySQL: Order by specific items first then by time
假设我们有一个 table
names
-------------------
id name created_at
1 alpha 2020-10-23 17:30:35
2 beta 2020-10-24 17:30:35
3 gamma 2020-10-25 17:30:35
4 kilo 2020-10-26 17:30:35
5 charlie 2020-10-27 17:30:35
6 hector 2020-10-28 17:30:35
我想按固定数组对前几行进行排序,比方说 6,3,2
,其余按 created_at
按降序排列。
所以我期望的顺序是 6,3,2,5,4,1
.
如何使用 Mysql 实现此目的?
我试过使用 field() 但无法让它与其他列一起使用。
一种选择是编写如下的 case 表达式
select *
from names
order by case when id in (6,3,2) then 0
else 1
end asc,created_at desc
SELECT * FROM names ORDER BY (
CASE
WHEN id = 6 THEN 1
WHEN id = 3 THEN 2
WHEN id = 2 THEN 3
ELSE 4
END, created_at DESC
)
CASE
语句确保列出的前 3 项是 6、3 和 2,其余按 created_at DESC
顺序列出。
FIELD()
对此很棘手,因为它 returns 0
如果没有匹配项。您可以构造一个表达式来执行您想要的操作:
order by coalesce(nullif(field(id, 6, 3, 2), 0), 999999),
created_at desc
如果您知道 id 对于固定值总是递减的,那么您可以使用:
order by (case when id in (6, 3, 2) then id end) desc,
created_at desc
假设我们有一个 table
names
-------------------
id name created_at
1 alpha 2020-10-23 17:30:35
2 beta 2020-10-24 17:30:35
3 gamma 2020-10-25 17:30:35
4 kilo 2020-10-26 17:30:35
5 charlie 2020-10-27 17:30:35
6 hector 2020-10-28 17:30:35
我想按固定数组对前几行进行排序,比方说 6,3,2
,其余按 created_at
按降序排列。
所以我期望的顺序是 6,3,2,5,4,1
.
如何使用 Mysql 实现此目的?
我试过使用 field() 但无法让它与其他列一起使用。
一种选择是编写如下的 case 表达式
select *
from names
order by case when id in (6,3,2) then 0
else 1
end asc,created_at desc
SELECT * FROM names ORDER BY (
CASE
WHEN id = 6 THEN 1
WHEN id = 3 THEN 2
WHEN id = 2 THEN 3
ELSE 4
END, created_at DESC
)
CASE
语句确保列出的前 3 项是 6、3 和 2,其余按 created_at DESC
顺序列出。
FIELD()
对此很棘手,因为它 returns 0
如果没有匹配项。您可以构造一个表达式来执行您想要的操作:
order by coalesce(nullif(field(id, 6, 3, 2), 0), 999999),
created_at desc
如果您知道 id 对于固定值总是递减的,那么您可以使用:
order by (case when id in (6, 3, 2) then id end) desc,
created_at desc