sql - 按特定顺序排序,包括NULL、postgresql

标签 sql postgresql

最好用一个例子来解释:

所以我有用户表:

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/

相关文章:

mysql - GROUP BY 仅具有不同值的同一字段

mysql - 如何组合两个查询,以便一个查询的结果将用于另一个查询?

sql - 查询以在IMPALA中一起显示所有列,表和模式名称

ruby-on-rails - Rails 左外连接与包含 NULL 的行

node.js - 我得到 - "TypeError: Client was passed a null or undefined query at Client.query",即使我的代码中没有 null 或 undefined

sql - 如何比较组中的行?

mysql - 使用 where 子句删除 MySQL 行

java - 出现错误 : cursor "<unnamed portal 1>" does not exist

Django Query 每天将两行中的值聚合为单个结果

postgresql - Azure kubernetes 上的 Postgres 卷权限错误