我有一個表,其中每個記錄包含他的父親,這個層次可能有多達6個級別。以下查詢搜索名爲「DEPARTMENT ABCD」的部門的所有家長。此查詢完美工作。Mysql - 如何選擇所有父母的孩子列表?
SELECT D2.id, D2.name, D2.id_parent
FROM (
SELECT
@d AS _id,
(SELECT @d := id_parent FROM department WHERE id = _id) AS id_parent,
@l := @l + 1 AS level
FROM
(SELECT
@d := (select id from department where name = 'DEPARTMENT ABCD'),
@l := 0
) initial_level,
department D
WHERE @d <> 0
) D1
JOIN department D2 ON D1._id = D2.id
ORDER BY D1.level DESC;
但是,如果我想在同一時間獲得超過一個孩子的父母(使用類似下面的查詢),我得到的錯誤:「錯誤代碼:1242子查詢返回多個1行」。
查詢並顯示錯誤「子查詢返回多個1行」:
SELECT D2.id, D2.name, D2.id_parent
FROM (
SELECT
@d AS _id,
(SELECT @d := id_parent FROM department WHERE id = _id) AS id_parent,
@l := @l + 1 AS level
FROM
(SELECT
@d := (select id from department where name like 'DEPARTMENT %A%'),
@l := 0
) initial_level,
department D
WHERE @d <> 0
) D1
JOIN department D2 ON D1._id = D2.id
ORDER BY D1.level DESC;
我怎麼能這樣做的同時獲得超過一個孩子的父母?
我加入SQL小提琴樣本:http://sqlfiddle.com/#!9/f182fb/3
如果我得到了你,你要顯示項目的層次結構。如果是這樣,你可以考慮選擇遞歸的方法,這裏描述http://stackoverflow.com/a/20216006/6435375 –
謝謝你的答案。我看到了鏈接,並且所描述的方法以列的形式顯示了級別,並且不支持尋找不止一個孩子的父母。 – David
你會爲你的數據創建一個小的小提琴樣本,甚至是假數據,所以我們可以測試結果嗎? (http://sqlfiddle.com) –