2010-04-27 210 views
30

如何獲得兩個結果集的集合差異?MySQL:兩個結果集的差異

說我有一個結果集(每個只有一個列):

result1: 
'a' 
'b' 
'c' 

result2: 
'b' 
'c' 

我要負什麼是在RESULT1通過RESULT2:RESULT1 - RESULT2使得它等於:

difference of result1 - result2: 
'a' 

回答

50

要執行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。它設置爲減法

參見:http://www.bitbybit.dk/carsten/blog/?p=71

+0

感謝您的澄清,我已經使用MySQL已經有一段時間了。 – 2010-04-27 18:30:09

9

如果你想在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),所以它們沒有設置差異,但也可能有用(可能比外部聯接效率更高)。