MySQL: difference of two result sets

后端 未结 3 868
暗喜
暗喜 2020-12-08 00:51

How can I get the set difference of two result sets?

Say I have a result set (just one column in each):

result1:
\'a\'
\'b\'
\'c\'

result2:
\'b\'
\'         


        
3条回答
  •  孤街浪徒
    2020-12-08 01:11

    If you want things in result1 that are not in result2, what about:

    SELECT distinct result1
    FROM t1 
    WHERE result1 NOT IN (select distinct result2 from t2);
    

    Or:

    SELECT distinct result
    from t1 t
    where NOT EXISTS (select 1 from t2 where result2 = t.result1)
    

    NOTE: if result1 is a subset of result2 then the above queries will return an empty set (they won't show you things in result2 that are not in result1) so they are not set difference, but may be useful too (probably it's more efficient than the outer join).

提交回复
热议问题