我有一个MySQL表,如下所示:
id |
name |
parent_id |
19 |
category1 |
0 |
20 |
category2 |
19 |
21 |
category3 |
20 |
22 |
category4 |
21 |
... |
... |
... |
现在,我想有一个单一的MySQL查询,我只是提供id[例如说id=19],然后我应该得到它的所有子id[即结果应该有id '20,21,22']....
孩子们的等级尚不清楚;它可以变化....
我知道如何使用for循环…但是如何使用一个MySQL查询来实现相同的功能呢?
这是一个有点棘手的问题,检查一下它是否适合你
select a.id,if(a.parent = 0,@varw:=concat(a.id,','),@varw:=concat(a.id,',',@varw)) as list from (select * from recursivejoin order by if(parent=0,id,parent) asc) a left join recursivejoin b on (a.id = b.parent),(select @varw:='') as c having list like '%19,%';
SQL小提琴链接http://www.sqlfiddle.com/#!2 / e3cdf / 2
用字段名和表名替换。
这是一个分类表。
SELECT id,
NAME,
parent_category
FROM (SELECT * FROM category
ORDER BY parent_category, id) products_sorted,
(SELECT @pv := '2') initialisation
WHERE FIND_IN_SET(parent_category, @pv) > 0
AND @pv := CONCAT(@pv, ',', id)
输出:
从博客管理分层数据在MySQL
表结构
+-------------+----------------------+--------+
| category_id | name | parent |
+-------------+----------------------+--------+
| 1 | ELECTRONICS | NULL |
| 2 | TELEVISIONS | 1 |
| 3 | TUBE | 2 |
| 4 | LCD | 2 |
| 5 | PLASMA | 2 |
| 6 | PORTABLE ELECTRONICS | 1 |
| 7 | MP3 PLAYERS | 6 |
| 8 | FLASH | 7 |
| 9 | CD PLAYERS | 6 |
| 10 | 2 WAY RADIOS | 6 |
+-------------+----------------------+--------+
查询:
SELECT t1.name AS lev1, t2.name as lev2, t3.name as lev3, t4.name as lev4
FROM category AS t1
LEFT JOIN category AS t2 ON t2.parent = t1.category_id
LEFT JOIN category AS t3 ON t3.parent = t2.category_id
LEFT JOIN category AS t4 ON t4.parent = t3.category_id
WHERE t1.name = 'ELECTRONICS';
输出
+-------------+----------------------+--------------+-------+
| lev1 | lev2 | lev3 | lev4 |
+-------------+----------------------+--------------+-------+
| ELECTRONICS | TELEVISIONS | TUBE | NULL |
| ELECTRONICS | TELEVISIONS | LCD | NULL |
| ELECTRONICS | TELEVISIONS | PLASMA | NULL |
| ELECTRONICS | PORTABLE ELECTRONICS | MP3 PLAYERS | FLASH |
| ELECTRONICS | PORTABLE ELECTRONICS | CD PLAYERS | NULL |
| ELECTRONICS | PORTABLE ELECTRONICS | 2 WAY RADIOS | NULL |
+-------------+----------------------+--------------+-------+
大多数用户都曾经在SQL数据库中处理过层次数据,毫无疑问,他们知道层次数据的管理不是关系数据库的目的。关系数据库的表不是分层的(像XML一样),而只是一个平面列表。层次数据具有亲子关系,在关系数据库表中不能自然地表示这种关系。
阅读更多
更多细节请参考博客。
编辑:
select @pv:=category_id as category_id, name, parent from category
join
(select @pv:=19)tmp
where parent=@pv
输出:
category_id name parent
19 category1 0
20 category2 19
21 category3 20
22 category4 21
参考:如何在Mysql中做递归SELECT查询?
这是一个有点棘手的问题,检查一下它是否适合你
select a.id,if(a.parent = 0,@varw:=concat(a.id,','),@varw:=concat(a.id,',',@varw)) as list from (select * from recursivejoin order by if(parent=0,id,parent) asc) a left join recursivejoin b on (a.id = b.parent),(select @varw:='') as c having list like '%19,%';
SQL小提琴链接http://www.sqlfiddle.com/#!2 / e3cdf / 2
用字段名和表名替换。