如何获得两个结果集的集差?
假设我有一个结果集(每列只有一列):
result1:
'a'
'b'
'c'
result2:
'b'
'c'
我想用 result2 减去 result1 中的内容: result1 - result2 等于:
difference of result1 - result2:
'a'
如何获得两个结果集的集差?
假设我有一个结果集(每列只有一列):
result1:
'a'
'b'
'c'
result2:
'b'
'c'
我想用 result2 减去 result1 中的内容: result1 - result2 等于:
difference of result1 - result2:
'a'
要执行result1 - result2,您可以将result1 与result2 连接起来,并且只输出result1 中存在的项目。例如:
SELECT DISTINCT result1.column
FROM result1 LEFT JOIN result2 ON result1.column = result2.column
WHERE result2.column IS NULL
请注意,这不是设置差异,并且不会输出 result2 中不存在于 result1 中的项目。设置减法。
另请参阅:相关博客文章的 Web 存档版本。
如果您想要 inresult1
中没有的东西result2
,那么:
SELECT distinct result1
FROM t1
WHERE result1 NOT IN (select distinct result2 from t2);
或者:
SELECT distinct result
from t1 t
where NOT EXISTS (select 1 from t2 where result2 = t.result1)
注意:如果result1
是 then 的子集,result2
则上述查询将返回一个空集(它们不会向您显示不在result2
的东西result1
),因此它们没有设置差异,但也可能有用(可能它比外部更有效加入)。
我最近有这个要求,我必须找到两个结果集之间的差异。尽管上述答案对我有所帮助,但希望它们能详细一点。对于给定的问题,我发现了两种解释:
对于结果集可以来自 2 个不同表的第一个,让我们使用两个表:science_student和math_student。
result1 - result2
result1: select student_id from science_student where id > 2
result2: select student_id from math_student
result1 - result2 之间的区别是 STUD3
因此,查找差异的查询将是:
select result1.student_id
from
(select student_id from science_student where id > 2) result1
left join
(select student_id from math_student) result2
on result1.student_id = result2.student_id
where result2.student_id is null;
对于结果集可以来自同一个表的第二种解释:
result1 - result2
result1: select student_id from science_student
result2: select student_id from science_student where id > 2
result1 - result2之间的区别是STUD1,STUD2
相同的查询将是:
select result1.student_id
from
(select student_id from science_student) result1
left join
(select student_id from science_student where id > 2) result2
on result1.student_id = result2.student_id
where result2.student_id is null;