2010-06-01 92 views
0

檢索數據我有一個包含ID,頂層菜單&的parentId的表自己的孩子一樣:MySql的來自同一個表

-------------------------------------- 
    id | name | parentId 
-------------------------------------- 
    1  | Color |  0 
-------------------------------------- 
    2  | Flower |  0 
-------------------------------------- 
    3  | Red  |  1 
-------------------------------------- 
    4  | pink |  1 
-------------------------------------- 
    5  | Rose |  2 
-------------------------------------- 
    6  | Lily |  2 
-------------------------------------- 

我想獲取這些記錄一些事情的結果數組必須像

--------------------------------------------------------------- 
    id | Pname | parentId | child | childId 
--------------------------------------------------------------- 
    1  | Color |  1  | Red  | 3 
--------------------------------------------------------------- 
    2  | Color |  1  | Pink | 4 
--------------------------------------------------------------- 
    3  | Flower |  2  | Rose | 5 
--------------------------------------------------------------- 
    4  | Flower |  2  | Lily | 6 
--------------------------------------------------------------- 

我的查詢語句,如:

SELECT name AS Pname FROM myTbl WHERE id = (SELECT parentId FROM myTbl WHERE parentId = 1) 

mysql的說#1242 - 子查詢返回多個1行

誰能解決呢? 謝謝..

回答

2
SELECT t1.id, t1.name AS Pname, 
    t2.parentId, t2.name as child, t2.id as childId 
FROM myTbl t1 
INNER JOIN myTbl t2 on t1.id = t2.parentId 
+0

少許change.SELECT t1.name爲 '父',t1.id爲 '父ID',t2.name爲 '兒童',t2.id爲「孩子ID' 從我的表t1 INNER JOIN mytable t2 ON t1.id = t2.parentId – 2010-12-21 09:04:24

1

問題出現了,因爲你的子查詢返回不止一行。 解決方案是確保該子查詢永遠只能返回一行,或以確保如果返回多個

但這些真的不給你,你的表建議你要

結果也沒關係
SELECT name AS Pname 
FROM myTbl 
WHERE id = (SELECT DISTINCT parentId 
       FROM myTbl 
       WHERE parentId = 1 
      ) 

OR

SELECT name AS Pname 
FROM myTbl 
WHERE id IN (SELECT DISTINCT parentId 
       FROM myTbl 
       WHERE parentId = 1 
      )