MySQL: difference of two result sets

徘徊边缘 提交于 2019-11-27 00:51:57

问题


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'
'c'

I want to minus what is in result1 by result2: result1 - result2 such that it equals:

 difference of result1 - result2:
 'a'

回答1:


To perform result1 - result2, you can join result1 with result2, and only output items that exist in result1. For example:

SELECT DISTINCT result1.column
FROM result1 LEFT JOIN result2 ON result1.column = result2.column
WHERE result2.column IS NULL

Note that is not a set difference, and won't output items in result2 that don't exist in result1. It's set subtraction.

See also: Web archive'd version of relevant blog post.




回答2:


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).



来源:https://stackoverflow.com/questions/2723839/mysql-difference-of-two-result-sets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!