[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 272
  • Last Modified:

sql joins

I need to join three tables. I want all 4 records from tableA and all matching records from tableB and tableC.  I end up with only 1 record.  In the end I only want 4 records and the data that matches.
SELECT   ui.ID, csct.description, csc.contact_type_acronym, csc.active, csc.date_added, ui.LastName + ', ' + ui.FirstName AS contactname, csct.acronym, csct.id as csctid
FROM         dbo.TableA AS csct LEFT OUTER JOIN   dbo.TableB AS csc ON csct.acronym = csc.contact_type_acronym 
LEFT OUTER JOIN dbo.TableC AS ui ON ui.ID = csc.contact_id
WHERE(csc.service_id = 196975) AND (csc.active = 1) AND (csct.ServiceLineID = '5') <-- this gives me the 4 records I need
ORDER BY csctid

Open in new window

0
lantervj
Asked:
lantervj
3 Solutions
 
derekkrommCommented:
Adding items to the where clause that are based on tables that are left joined basically results in an inner join on those columns.

If you move the 2 "csc.service_id = ..." and "csc.active = 1" clauses to the join portion, it should return the desired results.

SELECT   ui.ID, csct.description, csc.contact_type_acronym, csc.active, csc.date_added, ui.LastName + ', ' + ui.FirstName AS contactname, csct.acronym, csct.id as csctid
FROM         dbo.TableA AS csct LEFT OUTER JOIN   dbo.TableB AS csc ON csct.acronym = csc.contact_type_acronym and csc.service_id = 196975 and csc.active = 1
LEFT OUTER JOIN dbo.TableC AS ui ON ui.ID = csc.contact_id
WHERE  (csct.ServiceLineID = '5') <-- this gives me the 4 records I need
ORDER BY csctid

Open in new window

0
 
ThomasianCommented:
SELECT ui.ID, csct.description, csc.contact_type_acronym, csc.active, csc.date_added, ui.LastName + ', ' + ui.FirstName AS contactname, csct.acronym, csct.id as csctid
FROM dbo.TableA AS csct LEFT OUTER JOIN
     dbo.TableB AS csc ON csct.acronym = csc.contact_type_acronym 
                          AND (csc.service_id = 196975) AND (csc.active = 1) LEFT OUTER JOIN
     dbo.TableC AS ui ON ui.ID = csc.contact_id
WHERE csct.ServiceLineID = '5'
ORDER BY csctid

Open in new window

0
 
raulggonzalezCommented:
Hi,

Your problem cannot be the joins, the solution should be in the WHERE clause because you reference there

(csc.service_id = 196975) AND (csc.active = 1)

which don't belong to TableA csct ...

Do SELECT * and check manually the values to see it better.


Cheers
0
 
lantervjAuthor Commented:
Fast, accurate results.  I like it.
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now