如何检查两个选择是否返回相同的ID

时间:2015-03-12 07:18:41

标签: sql

假设我们有这样的查询:

SELECT
1
FROM DUAL WHERE  
(SELECT id FROM table_1 t1 WHERE /*conditions*/)
IN
(SELECT id FROM table_1 t2 WHERE /*conditions*/)

我想检查是否第一次查询 SELECT id FROM table_1 t1 WHERE /*conditions*/ 返回与第二个查询相同的ID。 当然,这个查询(IN语句)不起作用。

4 个答案:

答案 0 :(得分:1)

尝试:

SELECT id FROM table_1 t1 WHERE /*conditions1*/ and id not in (SELECT id FROM table_1 t2 WHERE /*conditions2*/)
union 
SELECT id FROM table_1 t1 WHERE /*conditions2*/ and id not in (SELECT id FROM table_1 t2 WHERE /*conditions1*/)

如果两个查询都给你相同的id,那么结果应为空。

答案 1 :(得分:0)

如果集合相等,则不返回任何内容:

SELECT id FROM table_1 t1 WHERE /*conditions*/
EXCEPT
SELECT id FROM table_1 t2 WHERE /*conditions*/

答案 2 :(得分:0)

您可以使用EXCEPT

  

EXCEPT返回左输入查询中不是的不同行   通过正确的输入查询输出。


您案件中的

EXCEPT样本:

SELECT id 
FROM   table_1 AS t1 
WHERE /*conditions*/
EXCEPT
SELECT id 
FROM   table_1 AS t2 
WHERE /*conditions*/

答案 3 :(得分:0)

就像在tsql 中使用Full Join 的替代方法一样:

SELECT CASE WHEN isnull(Count(*), 0) > 1 then 1 else 0 end as result
FROM    (SELECT t1.id as t1_id, t2.id as t2_id FROM 
            (SELECT id FROM table1 WHERE /*conditions*/) As t1 
            Full Outer Join 
            (SELECT id FROM table2 WHERE /*conditions*/) As t2 
    On t1.id = t2.id
    ) As ft
WHERE ft.t1_id is null or ft.t2_id is null

我认为这可以说是一种愚蠢的方式。