简体   繁体   中英

SQL to JOIN on two different columns

Our CRM software has a relationship function which allows you to define a relationship between two contacts. The contacts are stored in the CONTACT table and the relationship is stored in CONTACT_CONTACT .

We relate a doctor contact to a patient contact. In the CONTACT_CONTACT table there is CONTACTID1 , CONTACTID2 , CONTACT1_ROLE , and CONTACT2_ROLE .

We query the CONTACT table for the initial CONTACT by using a ClientID. Then we use the CONTACTID to do aa table join. The problem here is that the CONTACTID we have could be in CONTACT_CONTACT.CONTACTID1 or CONTACT_CONTACT.CONTACTID2 columns.

SELECT c2.CONTACT,
   c2.ClientID,
   c2.CONTACTID
FROM CONTACT as c
INNER JOIN CONTACT_CONTACT as cc on c.CONTACTID = cc.CONTACTID2
INNER JOIN CONTACT as c2 on cc.CONTACTID1 = c2.CONTACTID
WHERE c.ClientID = 121695 AND (cc.CONTACT1_ROLE = 'Doctor' OR cc.CONTACT2_ROLE = 'Doctor')

Same issue for joining back to the CONTACT table for the contact with the Doctor role listed in CONTACT_CONTACT .

If the contact or doctor can be in either CONTACT_CONTACT.CONTACTID1 or CONTACTID2 , what would be the best way to go about this without the possibility of changing the database tables?

COALESCE should work. However, if you have values in both fields, the join will execute on the field you list first inside the parentheses.

SELECT c.CONTACT,
   c.ClientID,
   c.CONTACTID
FROM CONTACT as c
INNER JOIN CONTACT_CONTACT as cc on c.CONTACTID = COALESCE(cc.CONTACTID1,cc.CONTACTID2)
WHERE c.ClientID = 121695 AND (cc.CONTACT1_ROLE = 'Doctor' OR cc.CONTACT2_ROLE = 'Doctor')

Couldn't you just do the query twice? There would be other ways to be sure, but this should get the information I think:

SELECT c.CONTACT,
   c.ClientID,
   c.CONTACTID
FROM CONTACT as c
INNER JOIN CONTACT_CONTACT as cc on c.CONTACTID = cc.CONTACTID1
INNER JOIN CONTACT as c2 on cc.CONTACTID2 = c2.CONTACTID
WHERE c.ClientID = 121695 
    AND cc.CONTACT1_ROLE = 'Doctor'
union
SELECT c2.CONTACT,
   c2.ClientID,
   c2.CONTACTID
FROM CONTACT as c
INNER JOIN CONTACT_CONTACT as cc on c.CONTACTID = cc.CONTACTID2
INNER JOIN CONTACT as c2 on cc.CONTACTID1 = c2.CONTACTID
WHERE c.ClientID = 121695 
    AND cc.CONTACT2_ROLE = 'Doctor'

I'm not really clear on what information you're hoping/attempting to get from your query, as you're only selecting from a single table's data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM