2016-05-28 40 views
0
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) 
+2

替换JOIN'这里的'所有实例(其是隐含一个'INNER JOIN')与'FULL OUTER JOIN','WHERE'安亚键(一个或多个)是'NULL'或任何乙键是'NULL'。语法显示在您裁剪的图像中:http://www.codeproject.com/KB/database/Visual_SQL_Joins/Visual_SQL_JOINS_orig.jpg –

+0

我知道这一部分,但我不知道要在WHERE子句中放置什么。谢谢你! – juice

+0

哦nvm,你编辑了你的评论。让我试试看。 – juice

回答

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 
+1

Where子句中的'null为空'的测试并不总是将完全外部缩减为左连接,右连接或内连接。特别是'LeftPK为null或RightPK为null'给出了没有匹配的两侧的行。 –