有没有办法使用单个查询获取父母及其子女?
CREATE TABLE `servers` (
`id` int NOT NULL AUTO_INCREMENT,
`name` varchar(20) NOT NULL,
`parent_id` int DEFAULT NULL,
PRIMARY KEY (`id`)
)
INSERT INTO servers (name) VALUES ('kvm01'), ('kvm02')
INSERT INTO servers (name, parent_id) VALUES ('web01', 1), ('db01', 1), ('web02', 2), ('db02', 2)
电流输出:
mysql [lab]> SELECT child.id FROM servers AS parent LEFT JOIN servers AS child ON (child.parent_id = parent.id) WHERE parent.name = 'kvm01';
+------+
| id |
+------+
| 3 |
| 2 |
+------+
2 rows in set (0.00 sec)
预期输出:
+------+
| id |
+------+
| 3 |
| 2 |
| 1 |
+------+