我正在努力构建一个MySql查询来识别表中缺少的行。
表T
结构如下:
+++++++++++++++++++++++++++++++++++++++++++++++
+ Unique ID + Group + Key1 + Key2 + Value +
+++++++++++++++++++++++++++++++++++++++++++++++
+ 34 + A + d1 + e2 + 123 +
+ 35 + A + d1 + e3 + 456 +
+ 36 + A + d1 + e1 + 444 +
+ 37 + A + d2 + e3 + 555 +
+ 38 + B + d1 + e3 + 555 +
+ 39 + B + d3 + e2 + 111 +
+ ... + ... + ... + ... + ... +
+++++++++++++++++++++++++++++++++++++++++++++++
行标记为A
和B
。我需要考虑A
和B
来确定组Key1
中的行集,而不是组Key2
中的行。表中只有Unique ID
是唯一的。
换句话说,查询应返回:
+++++++++++++++++++++++++++++++++++++++++++++++
+ Unique ID + Group + Key1 + Key2 + Value +
+++++++++++++++++++++++++++++++++++++++++++++++
+ 34 + A + d1 + e2 + 123 +
+ 36 + A + d1 + e1 + 444 +
+ 37 + A + d2 + e3 + 555 +
+++++++++++++++++++++++++++++++++++++++++++++++
答案 0 :(得分:1)
我会使用not exists
;
select ta.*
from t ta
where ta.group = 'A' and
not exists (select 1
from t tb
where tb.group = 'B' and tb.key1 = ta.key1 and tb.key2 = ta.key2
);
在MySQL中,您还可以使用多列in
:
select ta.*
from t ta
where ta.group = 'A' and
(ta.key1, ta.key2) not in (select tb.key1, tb.key2 from t tb where tb.group = 'B');
我更喜欢not exists
,因为许多数据库不支持多列in
。