【发布时间】:2011-02-13 00:13:07
【问题描述】:
如何获得两个结果集的集差?
假设我有一个结果集(每列只有一列):
result1:
'a'
'b'
'c'
result2:
'b'
'c'
我想用 result2 减去 result1 中的内容:result1 - result2 等于:
difference of result1 - result2:
'a'
【问题讨论】:
标签: mysql set-difference
如何获得两个结果集的集差?
假设我有一个结果集(每列只有一列):
result1:
'a'
'b'
'c'
result2:
'b'
'c'
我想用 result2 减去 result1 中的内容:result1 - result2 等于:
difference of result1 - result2:
'a'
【问题讨论】:
标签: mysql set-difference
执行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中的项。它设置了减法。
【讨论】:
如果你想要result1 中没有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 是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;
【讨论】: