postgresql - 查询时首先返回带空列的行(列 =?或列为空)

标签 postgresql

我正在尝试创建一个表来存储通知设置。在此表中,通知设置具有 typeuser_idoptions 列。任何具有 NULL user_id FK 的行都表示默认设置值,用户对其设置所做的任何更改都会使用他们的 user_id 更新到表中。

我的 User#fetchSettings 函数接受要获取的类型数组,如果没有提供类型,则获取所有类型。该函数应为每个请求的类型返回一个设置,返回带有 user_id 的行,而不是 user_id 为 NULL 的行。但是,我找不到一种方法让设置为 user_id 的行优先于设置为 NULL 的行。

我的查询如下:

select distinct ON (type) 
    "type", 
    "options",
    "user_id"
from "user_settings"
where 
    (
        "user_settings"."user_id" = '1' 
        or "user_id" is null
    ) 
and "type" in ('type1', 'type2', 'type3');

最佳答案

您可以通过 DISTINCT ON ("type") 选择行。当有多行具有相同类型时,这将选择集合的第一行。通过对行进行正确排序,您可以优先使用具有特定 user_id 的行而不是具有 null 值的行:

select distinct ON (type) 
    "type", 
    "options",
    "user_id"
from "user_settings"
where 
    (
        "user_settings"."user_id" = '1' 
        or "user_id" is null
    ) 
and "type" in ('type1', 'type2', 'type3')
order by 1, 2, 3 nulls last;

关于postgresql - 查询时首先返回带空列的行(列 =?或列为空),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39080829/

相关文章:

Python 和 Psycopg2 |具有不同 WHERE 子句的动态查询

sql - Postgresql:使用 Join 将多个几何合并为单个几何

postgresql - 如何在postgres中获得前几个月的范围

sql - 测试正常时正则表达式无法正常工作

PostgreSQL:使用 json 对象从数组中删除键/值对

mysql - PostgreSQL 上的公式查询

function - Postgres 函数结束循环并返回错误

ajax - 处理数据库中的 AJAX 并发问题

postgresql - 使用CASE查找某个整数并返回一个字符串

python - psycopg2.ProgrammingError : syntax error at or near "\"