2017-01-22 91 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

相關問題