2つの結果セットのセット差を取得するにはどうすればよいですか?
結果セットがあるとします(それぞれに1つの列のみ):
result1:
'a'
'b'
'c'
result2:
'b'
'c'
result1にあるものをresult2でマイナスしたい:result1-result2は、次のようになります。
difference of result1 - result2:
'a'
2つの結果セットのセット差を取得するにはどうすればよいですか?
結果セットがあるとします(それぞれに1つの列のみ):
result1:
'a'
'b'
'c'
result2:
'b'
'c'
result1にあるものをresult2でマイナスしたい: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
これはセットの違いではなく、result1に存在しないアイテムをresult2に出力しないことに注意してください。セット減算です。
関連するブログ投稿のWebアーカイブバージョンも参照してください。
にないものが必要な場合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つの結果セットの違いを見つけなければならないというこの要件がありました。上記の答えは私がそれらが少し詳細であることを望んだのを助けましたが。与えられた質問に対して、私は2つの解釈を見つけました:
結果セットが2つの異なるテーブルからのものである可能性がある最初のテーブルについては、 science_studentとmath_studentの2つのテーブルを取り上げましょう。
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;
結果セットが同じテーブルからのものである可能性がある2番目の解釈の場合:
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;