2013-04-26 87 views
0

我希望能夠查詢MySQL數據庫,以便根據他們的父母和孩子找到一個人的兄弟姐妹。我們假設在這裏假設一個人的父母的孩子以及一個人的孩子的父母是該人的兄弟姐妹。MySQL INNER JOIN與WHERE條件的結果?

id name 
----------- 
1 jonny 
2 tom 
3 sally 
4 bill 
5 katie 
6 jessica 

RELS

id parent child 
-------------------- 
1 2  3 
2 5  6 
3 2  1 
4 1  6 
5 1  4 
6 6  2 

我一直在試圖找出如何加入,讓我這些結果的方式這兩個表,但我可以沒有對的。

SELECT people.id,people.name FROM people, rels 
INNER JOIN rels children ON people.id = rels.parent 
INNER JOIN rels siblings ON children.id = siblings.child 
WHERE children.child = '1' 
+0

什麼是'思想'? – 2013-04-26 23:09:39

+0

哈哈,對不起 - 打字錯誤:p分心打字時> _ < – 2013-04-26 23:11:20

回答

0

試試這個

SELECT people.id,people.name FROM people 
    LEFT JOIN rels children ON people.id = children.parent 
    LEFT JOIN rels siblings ON people.id = siblings.child 
    WHERE children.child = '1' 
    group by people.id 

DEMO HERE

+0

我認爲這是接近,但莎莉應該返回以及。她是湯姆的孩子,是湯尼的父母。我嘗試了「SELECT people.id,people.name FROM people LEFT JOIN rels children people.id = children.parent LEFT JOIN rels parents on people.id = parents.child LEFT JOIN rels siblings ON people.id = siblings .child WHERE children.child ='1'OR parents.parent ='1' group by people.id「 - 抱歉格式化,但是也返回了一個賬單,他只是jonny的一個孩子。 – 2013-04-26 23:50:05

+0

是的,當孩子是1(jonny)那麼你得到了他的父母(湯姆),並希望得到莎莉意味着你想得到進入(jonny)1的兄弟/姐妹?因爲莎莉和喬尼有同樣的父母。所以你不想得到父母,你想得到兄弟? – 2013-04-27 10:51:57

+0

你可以編輯你的問題,並顯示你想要的結果嗎? – 2013-04-27 10:54:03

0

我用工會,我認爲這會爲現在做的拿出一個解決方案。如果任何人都可以想出一個純粹基於JOIN的解決方案,我很樂意看到它!

SELECT people.*,c.* FROM rels 
    INNER JOIN rels c ON rels.parent = c.parent 
    INNER JOIN people ON people.id = c.child 
    WHERE rels.child = '1' AND people.id <> '1' 

UNION 

SELECT people.*,p.* FROM rels 
    INNER JOIN rels p ON rels.child = p.child 
    INNER JOIN people ON people.id = p.parent 
    WHERE rels.parent = '1' AND people.id <> '1' 

http://sqlfiddle.com/#!2/45ba3/103/0

0

我沒有測試過這一點,但是這應該工作:

SELECT ppl.* from people as ppl 
INNER JOIN rels AS par1 on ppl.id = par1.child 
INNER JOIN rels as par2 on par2.parent = par1.parent 
INNER JOIN people as sib on sib.id = par2.child 
WHERE ppl.id = '3' 

說明服用例如薩莉(ID = 3)

從PPL選擇的人兄弟姐妹將被找到。 (id = 3)

從PAR1(父級)中選擇其父級。家長= 2選擇

從PAR2(家長)選擇相同的父父= 2選擇

從SIB(人)選擇細節其中id = 3,1

不要讓我知道如果這樣做不工作...