在查询时,列w / null列首先返回(列=?OR列为空)

时间:2016-08-22 13:25:29

标签: postgresql

我正在尝试创建一个用于存储通知设置的表。在此表中,通知设置包含typeuser_idoptions列。任何具有NULL user_id FK的行都代表默认设置值,用户对其设置所做的任何更改都将使用user_id上传到表中。

我的User#fetchSettings函数接受要提取的类型数组,如果没有提供类型,则提取所有类型。该函数应返回所请求的每种类型的设置,在user_id为NULL的行上返回行user_id的行。但是,我找不到让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');

2 个答案:

答案 0 :(得分:2)

您可以按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;

答案 1 :(得分:0)

在发布问题后不久就想出来了。通过添加order by子句,我能够在设置了user_ids的行之后放置空值。我的新查询是:

select distinct ON (type) 
    "type", 
    "description", 
    "options", 
    "user_id" 
from "user_settings"
where 
    (
        "user_settings"."user_id" = '385' 
        or "user_id" is null
    ) 
    and "type" in (...) 
order by "type" asc, "user_id" asc;