具有条件的2个表的SQL连接条件

时间:2018-07-06 11:08:56

标签: mysql sql

您知道如何仅在表中显示col3不是'X'的相同ID的行吗?

表1:

    ID | col1 | col2 |   
     ---+-----+-----+   
    1 | 0     | 0    |    
    1 | D     | C    |    
    1 | D     | C    |    
    2 | 0     | 0    |    
    2 | D     | C    |    
    2 | D     | C    |   
    3 | D     | C    |   
    3 | D     | C    |   
    3 | D     | C    |

表2:

     ID | col1 | col2 | col3
     ---+------+------+-----
      1 | 0    | 0    | X
      1 | D    | C    | null
      1 | D    | C    | null
      2 | 0    | 0    | null
      2 | D    | C    | null
      2 | D    | C    | null

例如,在上面的两个表格中,它应显示为结果:

    ID | col1 | col2 | 
     ---+------+------+
      2 | 0    | 0    | 
      2 | D    | C    | 
      2 | D    | C    | 
      3 | D    | C    | 
      3 | D    | C    | 
      3 | D    | C    | 

ID 2(因为所有col3为空)和ID 3(因为它在表1中,但不在表2中,所以就像它为null,或者它没有任何col3 = X)

它应该适用于所有ID逐行排列的所有ID,并且仅适用于表2中只有表1中不存在或不存在所有行的同一ID。

这是我尝试过的:

    select 
    T.id, T2.col1, T2.col2
    from table1 T 
    inner JOIN table2 T2 on T.ID=T2.ID
    where Cond1
    and T.ID NOT IN 
    (SELECT T2.ID FROM table2 T2 
    WHERE T.ID=T2.ID 
    AND T2.COL3='X') it displays only half of what i want :  ID | col1 | col2 | 
 ---+------+------+
  2 | 0    | 0    | 
  2 | D    | C    | 
  2 | D    | C    | 

我也需要同时拥有ID = 2和ID = 3:

3 | D    | C    | 
  3 | D    | C    | 
  3 | D    | C    | 

谢谢

2 个答案:

答案 0 :(得分:2)

我认为您只想要not exists

select t1.*
from t1
where not exists (select 1
                  from t2
                  where t2.id = t.id and t2.col3 = 'X'
                 );

答案 1 :(得分:0)

您应该在col3!='X'

的不同选择上使用内部联接
select * from table1 
inner  join (
select distinct id from table2 
where col3 !='X' 
) t on t.id = table1.id
相关问题