我正在尝试获取符合父子关系的所有行。 例如
id Title parent_id
1200 A 1000
1201 B 1000
1202 C 1000
1203 D 1000
1204 E 1200
1205 F 1200
1206 G 1201
1207 H 1205
1208 I 1205
1209 J 1205
现在我有1209 id,我想检索满足1209的父子关系船的所有行。就像这里1209涉及1205,1205涉及1200,1200涉及1000。
我试过了这个查询
SELECT * FROM `category` a left join category b on a.id=b.parent_id where a.id=1209
但这只给了我一条记录。我们正试图获得这种关系中的所有行。
答案 0 :(得分:7)
如果你只是寻找它的父母,祖父母,曾祖父母,你可以使用这样的东西。
SELECT id,title,parent_id FROM
(SELECT id,title,parent_id,
CASE WHEN id = 1209 THEN @id := parent_id
WHEN id = @id THEN @id := parent_id
END as checkId
FROM Test
ORDER BY id DESC) as T
WHERE checkId IS NOT NULL
如果你想找到所有的孩子,以及一个id的大孩子或大孩子,你可以使用这个
SELECT id,title,parent_id FROM
(SELECT id,title,parent_id,
CASE WHEN id = 1200 THEN @idlist := CONCAT(id)
WHEN FIND_IN_SET(parent_id,@idlist) THEN @idlist := CONCAT(@idlist,',',id)
END as checkId
FROM Test
ORDER BY id ASC) as T
WHERE checkId IS NOT NULL
sqlfiddle for finding children
查询寻找多个孩子的所有父母/祖父母/曾祖父母
SELECT id,title,parent_id FROM
(SELECT id,title,parent_id,
CASE WHEN id in (1209,1206) THEN @idlist := CONCAT(IFNULL(@idlist,''),',',parent_id)
WHEN FIND_IN_SET(id,@idlist) THEN @idlist := CONCAT(@idlist,',',parent_id)
END as checkId
FROM Test
ORDER BY id DESC)T
WHERE checkId IS NOT NULL