有没有办法使用单个查询获取父母及其子女?
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 |
+------+
您可以调整您的加入条件
或使用
UNION
/UNION ALL
分别检索父记录:https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=4f41816149af8751cf109a4e1c0a249e