2011-04-20 26 views
0

我需要在查詢中多次加入包含名稱的聯繫人表(聯繫人),以便同時獲得父級和子級名稱。我還需要加入一個擁有父子關係的表,以便知道哪個孩子屬於哪個父母(childs_caregiver)。下面的查詢是讓我父母和孩子的名字,但沒有將正確的父母附加到孩子 - 它只是運行所有可能的記錄。我不知道如何正確加入親子關係表(由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 

感謝您的期待!

回答

0

您正在加入c,ctctschilds_caregivers,但不是彼此相加。如果在多個contact記錄之間存在層次關係,則需要在DDL(模式)中表達這一點。爲parent_id添加一列,併爲「子」記錄添加一列,爲contact指定「父」的主鍵。然後在您的WHERE語句中加入contact表。

+0

感謝您的帶頭人。我不太清楚如何做到這一點,但迄今爲止(這使我沒有記錄,所以我知道這是錯誤的!):選擇c.contactid,c.contactid, c.lastname作爲'父姓', c.firstname'Parent First Name',c.address,c.city, c.state,c.postalcode,c.homephone,c.workphone,c.lastname as'Child Last Name',c.firstname as'兒童名字' 來自聯繫人c inner join childs_caregivers cv on c.contactid = cv.childcaregiverid 其中c.caregiver = 1和(contactid = caregiverid)和(contactid = childid) – WixLove 2011-04-20 16:22:29

+0

好吧 - 我只是重新讀你的回答和建議來更改表格而不是查詢。我對此很青澀,所以沒有聽清楚。好的 - 知道了。謝謝你的幫助! – WixLove 2011-04-20 21:05:13

+0

@WixLove - 很高興我能幫到你! – 2011-04-20 21:06:39