使用多个连接语句进行完全外连接的逻辑是什么?

时间:2016-05-28 00:52:28

标签: sql-server full-outer-join

SELECT MP.*
FROM SurveyFrontend..WebResult WR
JOIN MeetingHistory MH
ON MH.WebResultID=WR.WebResultID
JOIN Meeting M
ON MH.MeetingID=M.MeetingID
JOIN MeetingPlanner MP
ON MP.MeetingPlannerID=M.MeetingPlannerID
WHERE PrimaryEntityID=2424
AND WR.TimeResultTaken>='1/1/2016'
AND CardSet=2

我查了一下,但是我找不到任何关于如何使用多个连接进行完全外连接的示例。我想拉出与上述查询完全相反的内容。

我该怎么做呢?

这正是我正在寻找的:

SQL FULL OUTER JOIN

更新的代码:

SELECT MP.*
FROM SurveyFrontend..WebResult WR
FULL OUTER JOIN MeetingHistory MH
ON MH.WebResultID=WR.WebResultID
FULL OUTER JOIN Meeting M
ON MH.MeetingID=M.MeetingID
FULL OUTER JOIN MeetingPlanner MP
ON MP.MeetingPlannerID=M.MeetingPlannerID
WHERE PrimaryEntityID=2424
AND WR.TimeResultTaken>='1/1/2016'
AND CardSet=2
AND (MH.WebResultID IS NULL
OR   MH.MeetingID IS NULL
OR   MP.MeetingPlannerID IS NULL
OR   WR.WebResultID IS NULL
OR   M.MeetingID IS NULL
OR   M.MeetingPlannerID IS NULL)

1 个答案:

答案 0 :(得分:1)

full outer join返回符合on条件的所有行和左表中不匹配条件所有行的所有行从右表不符合条件。任何where限制都会将full outer join缩减为leftrightinner join。一些例子:

create table #a(id int, name varchar(10))
insert #a values (1,'test1'),(2,'test2'),(3,'test3')
create table #b(id int, name varchar(10))
insert #b values (1,'test1'),(4,'test4'),(5,'test5')

select a.id aid,a.name aname, b.id bid,b.name bname
from #a a full outer join #b b on a.id=b.id

--same as left join
select a.id aid,a.name aname, b.id bid,b.name bname
from #a a full outer join #b b on a.id=b.id
where a.id=2

--same as right join
select a.id aid,a.name aname, b.id bid,b.name bname
from #a a full outer join #b b on a.id=b.id
where b.id=4

--same as inner join
select a.id aid,a.name aname, b.id bid,b.name bname
from #a a full outer join #b b on a.id=b.id
where a.id=1 and b.id=1

--same as inner join better example
select a.id aid,a.name aname, b.id bid,b.name bname
from #a a full outer join #b b on a.id=b.id
where a.id = b.id