0

我有一个表,其中包含顶级菜单的idnameparentId及其子项,例如:

--------------------------------------
    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 行

任何人都可以解决它吗?谢谢..

4

2 回答 2

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
于 2010-06-01T15:30:13.800 回答
1

出现问题是因为您的子查询返回不止一行。解决方案是确保子查询只返回一行,或者确保它返回更多并不重要

但是这些并不能真正给您表格建议您想要的结果

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

或者

SELECT name AS Pname 
 FROM myTbl 
WHERE id IN ( SELECT DISTINCT parentId 
                FROM myTbl 
               WHERE parentId = 1 
            )
于 2010-06-01T15:28:54.593 回答