选择不在同一个表上的多个字段

时间:2017-01-22 14:39:08

标签: mysql sql

我正在努力构建一个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。我需要考虑AB来确定组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   + 
+++++++++++++++++++++++++++++++++++++++++++++++ 

1 个答案:

答案 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