私のクエリを構成する助けが必要です。私はサブクエリが必要だと思うが、私はそれを私の文脈でどのように使うべきかについてはあまりよく分かっていない。 、私は一種の何が起こっているかを理解し、私は、次のテーブルとデータを持っている、私のクエリからの出力はあまり適切ではないかもしれませんが、おそらくサブクエリですか?
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を使用していますか? –