Postgresql:检查列是否同时等于多个值的最佳方法

时间:2016-08-04 18:50:36

标签: sql postgresql relational-division

如果我想检查列是否等于一个值或其他值,我写道:

where col1 in (1, 4, 9);

但是如果我想检查列是否同时等于这些值, 我应该写:

where col1 = 1 and col1 = 4 and col1 = 9;

SQL中是否有任何简短形式,例如?

示例:

c1  |  c2
----------- 
1   |  1
1   |  2
1   |  3

从tablename中选择c1,其中c2 = 1且c2 = 2;

在结果集中,我想 1

2 个答案:

答案 0 :(得分:1)

PostgreSQL已将<operator> ALL合成伙伴扩展到数组,因此您可以使用:

WHERE col1 = ALL (ARRAY[1, 4, 9])

答案 1 :(得分:1)

关系师:

CREATE TABLE ztable
        ( c1 integer not NULL
        , c2 integer not null
        , PRIMARY KEY (c1,c2)
        );
INSERT INTO ztable(c1,c2) values
 (1   ,  1) -- [c1=1] should match
,(1   ,  2)
,(1   ,  3)
,(2   ,  3) -- [c1=2] should NOT match
,(2   ,  4)
        ;

WITH musthave (val) AS (VALUES (1), (2))
SELECT distinct c1
FROM ztable zt
WHERE NOT EXISTS ( -- we DONT WANT the records
        SELECT * FROM musthave mh
        WHERE NOT EXISTS ( -- for which one of the musthaves is missing
                SELECT * FROM ztable nx
                WHERE nx.c1 = zt.c1
                AND nx.c2 = mh.val
                )
        )
        ;

- 对于较小的问题(有限的一组必须值),您可以这样做:

SELECT distinct c1
FROM ztable zt
WHERE zt.c2 = 1
AND EXISTS (
        SELECT *
        FROM ztable t2
        WHERE t2.c1 = zt.c1
        AND t2.c2 = 2
        );

- 还有另一种方法,它计算匹配的c2值:

SELECT DISTINCT zt.c1
FROM ztable zt
JOIN    (
        SELECT c1, COUNT(DISTINCT c2) AS cnt
        FROM ztable t2
        WHERE t2.c2 IN (1, 2)
        GROUP BY c1
        ) zzz ON zzz.c1= zt.c1
WHERE zzz.cnt = 2
    ;