MySQL自关联表
2019-08-19 本文已影响0人
zxhChex
create table node_tree( id int not null auto_increment primary key, node_name varchar(128) not null default '', up_node_id int, node_level char(1) )ENGINE=InnoDB default charset=utf8 collate=utf8_swedish_ci;
insert into node_tree(node_name,up_node_id,node_level) values('jx',null,'1'),('jx.webserver',1,'2'),('jx.webserver.nginx1', 2, '3'), ('jx.logserver', 1, '2');
![](https://img.haomeiwen.com/i18938642/0a2eb847b36775a9.png)
![](https://img.haomeiwen.com/i18938642/ee7d5e662f89e8cf.png)
![](https://img.haomeiwen.com/i18938642/d07faa0552064270.png)
![](https://img.haomeiwen.com/i18938642/d506eed2207acd92.png)
select
node_tree1.id as 主表ID,
node_tree1.name as 主表名字,
node_tree2.name as 从表名字,
node_tree2.up_id as 从表上级ID
from node_tree1, node_tree2
where node_tree1.name='jx';
![](https://img.haomeiwen.com/i18938642/dd41446aea08806f.png)
select
node_tree1.id as 主表ID,
node_tree1.node_name as 主表名字,
node_tree2.node_name as 从表名字,
node_tree2.up_node_id as 从表上级ID
from node_tree as node_tree1, node_tree as node_tree2
where node_tree1.node_name='jx';
![](https://img.haomeiwen.com/i18938642/e4e5a8f1c2e0f307.png)
![](https://img.haomeiwen.com/i18938642/71dabac8a3c125e7.png)