mysq递归查询完整sql
时间: 2023-07-20 17:08:10 浏览: 98
递归查询是指在一个表中,通过某个字段的父子关系,查询出该字段下的所有子孙节点。MySQL中可以使用WITH RECURSIVE语句进行递归查询,具体示例如下:
假设有一个表employee,包含字段id、name、parent_id,其中parent_id表示该员工的上级员工ID。
```
CREATE TABLE employee (
id INT PRIMARY KEY,
name VARCHAR(50),
parent_id INT
);
INSERT INTO employee VALUES (1, 'A', NULL);
INSERT INTO employee VALUES (2, 'B', 1);
INSERT INTO employee VALUES (3, 'C', 1);
INSERT INTO employee VALUES (4, 'D', 2);
INSERT INTO employee VALUES (5, 'E', 2);
INSERT INTO employee VALUES (6, 'F', 4);
INSERT INTO employee VALUES (7, 'G', 5);
```
要查询员工A的所有下属员工,可以使用以下SQL语句:
```
WITH RECURSIVE subordinates AS (
SELECT id, name, parent_id
FROM employee
WHERE id = 1
UNION ALL
SELECT e.id, e.name, e.parent_id
FROM employee e
JOIN subordinates s ON e.parent_id = s.id
)
SELECT * FROM subordinates;
```
在这个例子中,首先查询出id为1的员工,然后通过UNION ALL和JOIN语句递归查询出所有该员工下属的员工。最终结果如下:
```
+----+------+-----------+
| id | name | parent_id |
+----+------+-----------+
| 1 | A | NULL |
| 2 | B | 1 |
| 3 | C | 1 |
| 4 | D | 2 |
| 5 | E | 2 |
| 6 | F | 4 |
| 7 | G | 5 |
+----+------+-----------+
```
阅读全文