最好用一个例子来解释:
所以我有用户表:
id name product
1 second NULL
2 first 27
3 first 27
4 last 6
5 second NULL
我想在这个产品订单中订购它们:[27,NULL, 6]
所以我会得到:
id name product
2 first 27
3 first 27
1 second NULL
5 second NULL
4 last 6
(注意 user id 3
可以在 user id 2
之前,因为它们具有相同的产品值)
现在没有 NULL 我可以这样做:
SELECT id FROM users ORDER BY users.product=27, users.product=6;
如何使用 NULL 来实现?
附注 我想对许多记录执行此操作,因此它应该是高效的。
最佳答案
您可以使用 case
生成自定义排序顺序:
select id
from users
order by case
when product = 27
then 1
when product is null
then 2
when product = 6
then 3
end
关于sql - 按特定顺序排序,包括NULL、postgresql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42187300/