需要一些幫助來構建我的查詢。我想我需要一個子查詢,但我不太清楚如何在我的上下文中使用它們。我有以下表和數據,從我的查詢輸出不太正確,可能子查詢呢?
people
ID, Name
1, David
2, Victoria
3, Brooklyn
4, Tom
5, Katie
6, Suri
7, Kim
8, North
9, Kanye
10,James
11,Grace
relationship
peopleID, Relationship, relatedID
3,Father,1
3,Mother,2
6,Father,4
6,Mother, 5
8,Mother,7
8,Mother,9
11,Father,10
我有以下查詢
SELECT DISTINCT p.ID, p.name, f.ID, f.name, m.ID, m.name
FROM people AS p
LEFT JOIN relationship AS fr ON p.ID = fr.peopleID
LEFT JOIN people AS f ON fr.relatedID = f.ID
LEFT JOIN relationship AS mr ON p.ID = mr.peopleID
LEFT JOIN people AS m ON mr.relatedID = m.ID
WHERE p.ID IN(3,6,8,11)
AND (
mr.Relationship IN('Mother','Stepmother')
OR fr.Relationship IN('Father','Stepfather')
)
上面的查詢輸出以下數據
3,Brooklyn,1,David,1,David
3,Brooklyn,1,David,2,Victoria
3,Brooklyn,2,Victoria,2,Victoria
6,Suri,4,Tom,4,Tom
6,Suri,4,Tom,5,Katie
6,Suri,5,Katie,5,Katie
8,North,7,Kim,7,Kim
8,North,9,Kanye,7,Kim
8,North,9,Kanye,9,Kanye
11,Grace,10,James,10,James
我有點明白是怎麼回事,因此我想我可能需要一個子查詢或者可能是一個工會來讓父母先獲得這些結果。我正試圖輸出以下內容,有誰能幫忙嗎?
3,Brooklyn,1,David,2,Victoria
6,Suri,4,Tom,5,Katie
8,North,9,Kanye,7,Kim
11,Grace,10,James,, <-should display no mother details (same for the father if father was not in the data)
你使用SQL Server? –