最好用一个例子来解释:
所以我有users表:
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来做呢?
附注:我想要为许多记录这样做,所以它应该是有效的。
发布于 2017-02-12 20:02:31
您可以使用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发布于 2017-02-12 23:46:38
需要注意的是,您可以遵循最初的方法。你只需要一个NULL-safe比较:
SELECT id
FROM users
ORDER BY (NOT users.product IS DISTINCT FROM 27)::int DESC,
(user.product IS NULL)::int DESC,
(NOT users.product IS DISTINCT FROM 6)::int DESC;你的版本有意想不到的结果的原因是因为第一次比较可以返回NULL,它是与"true“和"false”分开排序的。
https://stackoverflow.com/questions/42187300
复制相似问题