2015-04-29 76 views
0

我想检查子查询的结果是否与数字列表相交。SQL。检查2个列表是否相交

我试图用这个查询

SELECT * FROM my_table mt WHERE 
    EXISTS (
    (SELECT at.id FROM another_table at where at.some_id = mt.id) 
     INTERSECT 
    (1,2,3,4) 
    ) 

(1, 2, 3, 4)将在运行时由应用程序来取代。

但我发现了错误:

ERROR: syntax error at or near "1" 

我怎么能解决这个问题?我正在使用PostgreSQL

+0

尝试'VALUES(1,2,3,4)'? –

回答

2

您可以使用值列表:

SELECT * FROM my_table mt 
WHERE 
    EXISTS (
    (SELECT at.id FROM another_table at where at.some_id = mt.id) 
     INTERSECT 
    VALUES (1),(2),(3),(4) 
    ); 

如果它是一个数字范围您也可以使用功能generate_series

SELECT * FROM my_table mt 
WHERE 
    EXISTS (
    (SELECT at.id FROM another_table at where at.some_id = mt.id) 
     INTERSECT 
    SELECT generate_series(1,4) 
    ); 

INTERSECT是没有必要的,但。您可以使用:

SELECT * FROM my_table mt 
WHERE 
    EXISTS 
    (SELECT 1 FROM another_table at where at.some_id = mt.id AND at.id IN (1,2,3,4)); 

或再次,如果它是一个范围:

SELECT * FROM my_table mt 
WHERE 
    EXISTS 
    (SELECT 1 FROM another_table at where at.some_id = mt.id AND at.id BETWEEN 1 AND 4); 
3

您可以使用VALUES生成一个 “常数表”,由INTERSECT消耗:

SELECT * FROM my_table mt WHERE 
    EXISTS (
    (SELECT at.id FROM another_table at where at.some_id = mt.id) 
     INTERSECT VALUES (1),(2),(3),(4) 
    ) 

SQL Fiddle Demo