代码之家  ›  专栏  ›  技术社区  ›  David Silva

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

sql
  •  0
  • David Silva  · 技术社区  · 11 年前

    假设我们有这样的查询:

    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 回复  |  直到 11 年前
        1
  •  1
  •   Jens    11 年前

    尝试:

    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,则结果应为空。

        2
  •  0
  •   Giorgi Nakeuri    11 年前

    如果集合相等,则不会返回任何结果:

    SELECT id FROM table_1 t1 WHERE /*conditions*/
    EXCEPT
    SELECT id FROM table_1 t2 WHERE /*conditions*/
    
        3
  •  0
  •   Stanislovas KalaÅ¡nikovas    11 年前

    您可以使用 EXCEPT .

    EXCEPT返回左侧输入查询中的不同行 通过右输入查询输出。


    EXCEPT 在您的案例中示例:

    SELECT id 
    FROM   table_1 AS t1 
    WHERE /*conditions*/
    EXCEPT
    SELECT id 
    FROM   table_1 AS t2 
    WHERE /*conditions*/
    
        4
  •  0
  •   shA.t Rami Jamleh    11 年前

    作为使用的替代方法 Full Join 在tsql中 :

    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
    

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