我的表格中包含 id ,名称, parentId 的顶级菜单&他们的孩子喜欢:
--------------------------------------
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行
有人能解决吗? 感谢..
答案 0 :(得分: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
答案 1 :(得分: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
)