ShadyBears
ShadyBears

Reputation: 4185

What is the logic behind doing a full outer join with multiple join statements?

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

I've looked it up but I can't find any examples on how to do a full outer join with multiple joins. I want to pull the exact opposite of the above query.

How would I go about doing this?

Here is exactly what I'm looking for:

SQL FULL OUTER JOIN

Updated code:

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)

Upvotes: 0

Views: 277

Answers (1)

Alex Kudryashev
Alex Kudryashev

Reputation: 9470

full outer join returns all rows which match on condition and all rows from left table which don't match condition and all rows from right table which don't match condition. Any where restrictions reduce full outer join to left, right, or inner join. Some examples:

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

Upvotes: 1

Related Questions