SQL Logic Help for Outer Joins with Foreign Keys

时间:2016-03-04 18:02:44

标签: sql sql-server

I have a situation where we have member data in table 'MEMBERS'. Then for each type of task assigned to a member, they are stored in 4 separate tables, PRSP_TASKS, PRSP_CALLS, PRSP_TOURS, and PRSP_EMAILS. Those four tables are linked back to the members table with a foreign key of memid = prospectid.

What I am attempting to do, is for each entry in the members table that was entered between two dates, to return all rows from each of the four tables. If there aren't any rows, then I still need to have one row signifying that.

I do not seem to be getting the records that are in the MEMBERS table but that have no rows in the other four tables.

SELECT MEMBERS.memid,
       MEMBERS.fname,
       MEMBERS.lname,
       MEMBERS.relationship,
       MEMBERS.employeeid,
       MEMBERS.entrydate,
       PRSP_TOURS.tourdate,
       PRSP_TOURS.tournote,
       PRSP_CALLS.calldate,
       PRSP_CALLS.callnote,
       PRSP_EMAILS.emaildate,
       PRSP_EMAILS.emailsubject,
       PRSP_TASKS.taskdate,
       PRSP_TASKS.tasknote
FROM   MEMBERS
       LEFT OUTER JOIN PRSP_TASKS
                    ON MEMBERS.memid = PRSP_TASKS.memid
       LEFT OUTER JOIN PRSP_TOURS
                    ON MEMBERS.memid = PRSP_TOURS.prospectid
       LEFT OUTER JOIN PRSP_CALLS
                    ON MEMBERS.memid = PRSP_CALLS.prospectid
       LEFT OUTER JOIN PRSP_EMAILS
                    ON MEMBERS.memid = PRSP_EMAILS.prospectid
WHERE  ( MEMBERS.siteid = @rvSite )
       AND ( MEMBERS.relationship = 'P' )
       AND ( MEMBERS.entrydate BETWEEN @rvEntryDateStart AND @rvEntryDateEnd ) 

0 个答案:

没有答案