多个联接仅返回匹配的字段

时间:2019-05-16 12:28:13

标签: sql join

需要运行多个联接,其中仅返回匹配的行。 我只想从匹配的行中获取值

我有这样的查询:

select dc.STATUSWORK "DC STATUS", de.STATUSWORK "DE STATUS", r.STATUSWORK "R STATUS", g.STATUSWORK "G STATUS", c.STATUSWORK "CONTRACT Status", c.PYID 
from CONTRACT c
join VDC dc on (dc.COVERKEY = c.KEY)
join VDE de on (de.COVERKEY = c.KEY)
join RCK r on (r.COVERKEY = c.KEY)
join GDE g on (g.COVERKEY = c.KEY)
join CDOC c on (c.COVERKEY = c.KEY)
where c.PYID = 'C-1000';

如果不是所有联接条件都匹配,则不会返回任何行,如果我使用某些左联接或右联接,还将返回NULL值的行

如何运行查询以检查匹配的行之前是什么,并提供新查询以仅返回匹配的表/行?

2 个答案:

答案 0 :(得分:0)

如果我正确理解您的要求,则应该这样做。只要它们在其他至少一行中具有匹配项,它将从Contract中返回所有行。如果您需要所有表都具有匹配项,请为AND切换OR。

select dc.STATUSWORK "DC STATUS"
   , de.STATUSWORK "DE STATUS"
   , r.STATUSWORK "R STATUS"
   , g.STATUSWORK "G STATUS"
   , c.STATUSWORK "CONTRACT Status", c.PYID 
from CONTRACT c
   left join VDC dc on (dc.COVERKEY = c.KEY)
   left join VDE de on (de.COVERKEY = c.KEY)
   left join RCK r on (r.COVERKEY = c.KEY)
   left join GDE g on (g.COVERKEY = c.KEY)
   left join CDOC c on (c.COVERKEY = c.KEY)
where c.PYID = 'C-1000'
and (
       exists (Select 1 from VDE where COVERKEY = c.KEY)
       or
       exists (Select 1 from VDC where COVERKEY = c.KEY)
       or
       exists (Select 1 from RCK where COVERKEY = c.KEY)
       or
       exists (Select 1 from GDE where COVERKEY = c.KEY)
       or
       exists (Select 1 from CDOC where COVERKEY = c.KEY)
);

答案 1 :(得分:0)

我已经模拟了几个表和一个查询,看这是否是您需要的。

create table CONTRACT(ConKey int, ConName varchar(20));

insert into CONTRACT(ConKey, ConName) Values(1, 'AAA');
insert into CONTRACT(ConKey, ConName) Values(2, 'BBB');
insert into CONTRACT(ConKey, ConName) Values(3, 'CCC');

create table VDC(VDCKey int, StatusWork varchar(20));  

insert into VDC(VDCKey, StatusWork) Values(1, 'Status 1');
insert into VDC(VDCKey, StatusWork) Values(3, 'Status 2');
insert into VDC(VDCKey, StatusWork) Values(4, 'Status 3');  

create table VDE(VDEKey int, StatusWork varchar(20));  

insert into VDE(VDEKey, StatusWork) Values(1, 'Status 4');
insert into VDE(VDEKey, StatusWork) Values(3, 'Status 5');
insert into VDE(VDEKey, StatusWork) Values(4, 'Status 6');  

create table RCK(RCKKey int, StatusWork varchar(20));  

insert into RCK(RCKKey, StatusWork) Values(5, 'Status 7');
insert into RCK(RCKKey, StatusWork) Values(2, 'Status 8');
insert into RCK(RCKKey, StatusWork) Values(1, 'Status 9');  

这是查询:-

Select c.ConKey, c.ConName, dc.StatusWork, de.StatusWork, r.StatusWork 
from CONTRACT c
LEFT JOIN VDC dc ON dc.VDCKey = c.ConKey
LEFT JOIN VDE de on de.VDEKey = c.ConKey
LEFT JOIN RCK r on r.RCKKey = c.ConKey;

这是结果:-

ConKey  ConName StatusWork  StatusWork  StatusWork
1       AAA     Status 1    Status 4    Status 9
2       BBB                             Status 8
3       CCC     Status 2    Status 5