mysql递归查询子类ID查询所有子类
先来看数据表的结构如下:
id name parent_id
---------------------------
1 Home 0
2 About 1
3 Contact 1
4 Legal 2
5 Privacy 4
6 Products 1
7 Support 1
我要的要求是根据一个分类ID(这个分类ID可能是一个子分类),得到所有的父分类,下面是相应的SQL:
SELECT ID.level, DATA.* FROM( SELECT @ids as _ids, ( SELECT @ids := GROUP_CONCAT(id) FROM table1 WHERE FIND_IN_SET(parent_id, @ids) ) as cids, @l := @l+1 as level FROM table1, (SELECT @ids :='5', @l := 0 ) b WHERE @ids IS NOT NULL ) id, table1 DATA WHERE FIND_IN_SET(DATA.id, ID._ids) ORDER BY level, id;