在Postgres中:在多个值上使用“ IS DISTINCT FROM”的最简洁方法是什么?

时间:2019-10-23 19:15:58

标签: sql postgresql

我正在尝试查找具有枚举列的所有行,该枚举列为NULL或与给定的枚举值集不同。我可以通过许多IS DINSTINCT FROM调用来做到这一点,但是它确实很冗长,我宁愿使用NOT IN()语法,但是NULL会把它扔掉。

这里是一个我想在SQL中执行的操作的示例,它来自这个小提琴:http://sqlfiddle.com/#!17/dfae4d/8


    CREATE TYPE mood AS ENUM ('sad', 'ok', 'happy');
    CREATE TABLE people (
        name text,
        current_mood mood,
        current_mood_as_text varchar
    );
    insert into people values('Mr Happy', 'happy', 'happy');
    insert into people values('Mr Sad', 'sad', 'sad');
    insert into people values('Mr Null', NULL, NULL);

    -- This doesn't return MrUnknown because of the NULL value:
    select * from people where current_mood NOT IN ('happy');

    -- This works great, and includes Mr Null:
    select * from people where current_mood IS DISTINCT FROM 'happy';

    -- But If I want to start comparing to multiple moods, it gets more verbose fast:
    SELECT * FROM people 
    WHERE current_mood IS DISTINCT FROM 'happy' AND
    current_mood IS DISTINCT FROM 'sad';

    -- You can't write this, but it's kinda what I want:
    -- SELECT * FROM people 
    -- WHERE current_mood IS DISTINCT FROM ('happy', 'sad');

    -- For the non enum column, I could do this to make my intention and code clear and concise
    SELECT * FROM people 
    WHERE coalesce(current_mood_as_text, '') NOT IN ('happy', 'sad');

    -- But if I write this, I get an error because '' is not a valid enum value
    -- SELECT * FROM people 
    -- WHERE coalesce(current_mood, '') NOT IN ('happy', 'sad');

还有另一种方法可以使这种多重比较更加简洁吗?

3 个答案:

答案 0 :(得分:1)

使用coalesce()的解决方案:

select * 
from people 
where coalesce(current_mood not in ('happy', 'sad'), true)

SQLFiddle.

答案 1 :(得分:0)

另一种方式:


SELECT * FROM people 
WHERE NOT EXISTS (
  SELECT FROM (VALUES ('happy'::mood), ('sad')) v(m)
  WHERE people.current_mood = v.m
);

答案 2 :(得分:0)

最干净(IMO)的方法是在CTE中使用VALUES()并对该表表达式执行NOT EXISTS()


WITH m(m) AS ( VALUES( 'happy'::mood) )
SELECT *
FROM people p
WHERE NOT EXISTS (
        SELECT * FROM m
        WHERE m.m = p.current_mood
        );