mysql - 来自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)
注意:我无法更改数据库架构。
解决方案
我想它可以帮助你
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))
它会找到你的起始节点的所有孩子
推荐阅读
- python - 在 Python 中使用 SAT 求解找到通过图中顶点的路径
- docker - 在docker compose中将文件夹名称附加到容器名称的目的是什么
- python - 如何从熊猫的下一个单元格中获取值?
- kubernetes - 如何在 Kubernetes 中传递动态环境变量
- sql - 使用 Oracle11g 将多行加入单行而不进行聚合
- javascript - React - 在不重置秒表的情况下刷新卡片
- spring-data-jpa - 按集合属性排序时重复的结果
- javascript - React 函数组件使用变量(不是状态)
- python - 训练期间 GPU 内存使用量增加
- php - 多次复制 MySQL 表中的行并添加附加列