MySQL 级联查询所有父级
MySQL 级联查询所有父级
表结构:
id | name | code | parent_code |
1 | 老板 | A | |
2 | 总经理 | B | A |
3 | 项目总监 | C | B |
4 | 开发工程师 | D | C |
查询D开发工程师的所有上级:
SELECT `name`, @`code` AS c_ids, ( SELECT @`code` := parent_code FROM depart WHERE `code` = @`code` ) AS p_ids FROM depart ,( SELECT @`code` := 'D' ) b
SQL 分析:
SELECT @`code`:= 'D' 的作用是 把'D'赋值给变量 @`code`
赋值的方法还有其他写法:
1、set @`code`='D';
2、set @`code`:='D';
3、select @`code`='D';
4、select @`code`= 字段名 from 表名 where ……
SELECT @`code` := parent_code FROM depart WHERE `code` = @`code`
不断的赋值与查询:
不断的查询 parent_code 并赋值给@`code` 通过WHERE条件不断的查询新值。
去重的写法:
SELECT u2.`code`, u2.`name` FROM ( SELECT @`code` AS c_ids , ( SELECT @`code` := parent_code FROM depart WHERE `code` = @`code` ) AS p_ids ,@l := @l + 1 AS LEVEL FROM depart, ( SELECT @`code` := 'D', @l := 0 ) b ) u1 JOIN depart u2 ON u1.c_ids = u2.`code`