MySQL:两个结果集的差异

时间:2010-04-27 18:19:54

标签: mysql set-difference

如何获得两个结果集的设置差异?

假设我有一个结果集(每个只有一列):

result1:
'a'
'b'
'c'

result2:
'b'
'c'

我想减去result2中result1的结果:result1 - result2使得它等于:

 difference of result1 - result2:
 'a'

3 个答案:

答案 0 :(得分:57)

要执行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中不存在的result2中的项目。它设置了减法

另请参阅:http://www.bitbybit.dk/carsten/blog/?p=71

答案 1 :(得分:13)

如果您希望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)

注意:如果result1result2的子集,那么上述查询将返回一个空集(他们不会向result2显示不在result1内的内容{1}})因此它们没有区别,但也可能有用(可能它比外部联接更有效)。

答案 2 :(得分:0)

我最近有这个要求,我必须找出两个结果集之间的差异。尽管以上答案帮助我希望它们有所详细。对于给定的问题,我发现了两种解释:

  1. 结果集可能来自2个不同的表
  2. 同一表中的结果集

对于第一个结果集可以来自2个不同表的表,让我们采用两个表: science_student math_student


science_student
enter image description here


数学学生
enter image description here


我想计算这两个结果集之间的差异,即:
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;
相关问题