在8之前一般都是写递归函数实现,
另一种方式:
*的解决方案,亲测有效:
SELECT * FROM person WHERE department IN (SELECT department_id FROM department WHERE department_id = 20006 UNION (SELECT department_id FROM (SELECT * FROM department ORDER BY parent_id,department_id) depart_sorted, (SELECT @pv := 20006) initialisation WHERE find_in_set(parent_id,@pv) AND length(@pv := concat(@pv,‘,‘,department_id))));
sql:
CREATE TABLE department ( id BIGINT(11) PRIMARY KEY NOT NULL AUTO_INCREMENT, department_id INT(11) NOT NULL, parent_id INT(11), department_level INT(2) NOT NULL, department_name VARCHAR(20), attend_group VARCHAR(20) );
如果是MySQL8则可以利用新特性CTE