[英]SQL join condition for 2 tables with conditions
您知道如何仅在表中显示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 |
谢谢
我想你只是想not exists
:
select t1.*
from t1
where not exists (select 1
from t2
where t2.id = t.id and t2.col3 = 'X'
);
您应该在col3!='X'的不同选择上使用内部联接
select * from table1
inner join (
select distinct id from table2
where col3 !='X'
) t on t.id = table1.id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.