我正在尝试创建一个表来存储通知设置。在此表中,通知设置具有 type
、user_id
和 options
列。任何具有 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/