I need to join a contact table (contacts) that contains names multiple times in a query in order to get both parent and child names. I also need to join a table that has the parent-child relationship so I know which child belongs to which parent (childs_caregiver). The below query is getting me parent and child names but not attaching the correct parent to child–it’s just running all possible records. I don’t know how to join the parent-child relationship table properly (by childcaregiverID).
select c.contactid, ct.contactid,
c.lastname as 'Parent Last Name', c.firstname as 'Parent First Name', c.address, c.city,
c.state, c.postalcode, c.homephone, c.workphone, ct.lastname as 'Child Last Name', ct.firstname as 'Child First Name'
from contacts c
inner join childs_caregivers cc on c.contactid=cc.caregiverid,
contacts ct
inner join childs_caregivers cs on ct.contactid=cs.childid,
contacts cts
inner join childs_caregivers cv on cts.contactid=cv.childcaregiverid
where c.caregiver=1
Thanks for looking!
You’re joining
c,ct, andctswithchilds_caregivers, but not with each other. If there is a hierarchical relationship between multiplecontactrecords, you need to express this in your DDL (schema). Add a column forparent_idand for “child” records, specify the primary key for thecontactthat is the “parent”. Then join thecontacttables together in your WHERE statement.