首页 > 解决方案 > 来自mysql的树枝

问题描述

我有带有模式whixh 的mysql 表,其中包含用于存储树结构的数据。

CREATE TABLE `treedata` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `parent_id` int(11) unsigned NOT NULL DEFAULT '0',
  `depth` tinyint(3) unsigned NOT NULL DEFAULT '0',
  `name` varchar(128) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uniquecheck` (`parent_id`,`name`) USING BTREE,
  KEY `depth` (`depth`) USING BTREE,
  KEY `parent_id` (`parent_id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=latin1

它有以下数据。

mysql> select * from treedata;
+----+-----------+-------+------+
| id | parent_id | depth | name |
+----+-----------+-------+------+
|  1 |         1 |     0 | root |
|  2 |         1 |     1 | b1   |
|  3 |         1 |     1 | b2   |
|  4 |         1 |     1 | b3   |
|  5 |         2 |     2 | b1_1 |
|  6 |         2 |     2 | b1_2 |
|  7 |         2 |     2 | b1_3 |
|  8 |         3 |     2 | b2_1 |
|  9 |         3 |     2 | b2_2 |
| 10 |         3 |     2 | b2_3 |
| 11 |         4 |     2 | b3_1 |
| 12 |         4 |     2 | b3_2 |
| 13 |         4 |     2 | b3_3 |
+----+-----------+-------+------+
13 rows in set (0.00 sec)

我需要根据深度和名称选择分支及其子项,例如如果深度为 1 且名称为 b1,那么它应该返回

+----+-----------+-------+------+
| id | parent_id | depth | name |
+----+-----------+-------+------+
|  2 |         1 |     1 | b1   |
|  5 |         2 |     2 | b1_1 |
|  6 |         2 |     2 | b1_2 |
|  7 |         2 |     2 | b1_3 |
+----+-----------+-------+------+

我是数据库新手。我试过左加入它给所有孩子但不是分支本身。

mysql> select td2.* from treedata as td1 left join treedata as td2 on td1.id=td2.parent_id where td1.name='b1';
+------+-----------+-------+------+
| id   | parent_id | depth | name |
+------+-----------+-------+------+
|    5 |         2 |     2 | b1_1 |
|    6 |         2 |     2 | b1_2 |
|    7 |         2 |     2 | b1_3 |
+------+-----------+-------+------+
3 rows in set (0.00 sec)

注意:我无法更改数据库架构。

标签: mysqlsql

解决方案


我想它可以帮助你

select  * from (select * from table_name order by `depth`) products_sorted,(select @pv := 'your_node_id(string)') initialisation where (find_in_set(parent_id, @pv) or id=your_node_id) and length(@pv := concat(@pv, ',', id))

它会找到你的起始节点的所有孩子


推荐阅读