2017-01-22 127 views
0

我正在努力构建一个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 + 
+ ...  + ... + ... + ... + ... + 
+++++++++++++++++++++++++++++++++++++++++++++++ 

行与标签AB分组。我需要通过考虑Key1Key2来识别组A中的一组行,但不在组B中,通过考虑Key1Key2。表中只有Unique ID是唯一的。

换句话说,查询应该返回:

+++++++++++++++++++++++++++++++++++++++++++++++ 
+ Unique ID + Group + Key1 + Key2 + Value + 
+++++++++++++++++++++++++++++++++++++++++++++++ 
+ 34  + A  + d1  + e2  + 123 + 
+ 36  + A  + d1  + e1  + 444 + 
+ 37  + A  + d2  + e3  + 555 + 
+++++++++++++++++++++++++++++++++++++++++++++++ 

回答

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

相关问题