I am trying to create a Select command to combine 3 tables.
GROUPS, I want to see every record of this table where the table meets the WHERE for the table CONTACTS, I want to see contacts that meet certain conditions, if there are no contacts I still want to see the GROUP records in the query GROUPCONTACTS, this table sits between GROUPS and CONTACTS to allow for a many-to-many relationship.
I have tried the following but it shows me every GROUPCONTACTS record instead of just those where there is a related CONTACTS that matches the query. I do not know if SQL allows for what I want.
Azure server running MSSQL server.
SELECT G.GroupID, GC.ContactID, C.ContactID, C.Status, C.Type
FROM Groups G
LEFT JOIN GroupContacts GC
ON GC.GroupID = G.GroupID
JOIN Contacts C
ON C.ContactID = GC.ContactID
AND C.Type = 'Manager'
AND C.Status = 'Active'
WHERE G.Status = 'Active' AND G.Type = 'Physician'
I was hoping to see 1951 results showing 1 record per GROUPS whether or not there was a matching CONTACT. Instead I got 1550 results, excluding all GROUPS that didn't have a matching CONTACT.
I hope I am explaining this well enough How can I have the table Contacts JOIN with GroupContacts and then in turn have the results LEFT JOIN with GROUPS?
Sample source tables GROUP
| GroupID | Type | Name | Status |
| ------------ | ------------ | ------------ | ------------ |
| 1 | Physician | Drs. Bennett & Stein | Active |
| 2 | Physician | Drs. Kogan & Larson | Inactive |
| 6 | Physician | Diagnostic Imaging | Active |
GROUPCONTACTS
| GroupContactID | GroupID | ContactID |
| ------------ | ------------ | ------------ |
| 13258 | 2227 | 124 |
| 13259 | 2305 | 138 |
| 13260 | 526 | 251 |
| 13261 | 2900 | 351 |
| 13262 | 1363 | 371 |
| 13263 | 2408 | 460 |
| 13264 | 417 | 511 |
CONTACTS
| ContactID | Type | First Name | Last Name | Status |
| ------------ | ------------ | ------------ | ------------ | ------------ |
| 375 | Physician | Mervyn L. | Elgart | Inactive |
| 376 | Physician | Stephen S. | Elgin | Inactive |
| 377 | Physician | Oscar | Ellison III | Active |
| 378 | Physician | Michael | Emmer | Active |
RESULTS (Ideal)
| GroupID | ContactID | ContactID | Status | Type |
| ------------ | ------------ | ------------ | ------------ | ------------ |
| 3177 | 36187 | 36187 | Active | Manager |
| 3178 | 36188 | 36188 | Active | Manager |
| 3179 | 36189 | 36189 | Active | Manager |
| 3180 | NULL | NULL | NULL | NULL |
If a GROUPS doesn't have a matching GROUPCONTACT record just show the last 4 fields as NULL. The reason for the 2 ContactIDs is just for testing purposes.
1条答案
按热度按时间gkl3eglg1#
Next time, please post the
CREATE TABLE
andINSERT INTO
setup statements. I created all those statements only to realize that the data inGroupContacts
table doesn't match any of the sample data inGroups
orContacts
. Fix the data. Include an example of data that is excluded but you think should be included. Then I'll update my answer.fiddle