mysql树操作

查询所有叶子节点

SELECT id FROM lsblj_department WHERE id NOT IN (SELECT parent_id FROM lsblj_department);

查询id为1下的所有部门

SELECT id,name,parent_id FROM (
SELECT t1.id,parent_id,t1.name,IF(FIND_IN_SET(parent_id, @pids) > 0, @pids := CONCAT(@pids, ‘,’, id), 0) AS ischild FROM
(SELECT id,parent_id,nameFROM lsblj_department) t1,
(SELECT @pids := 1) t2
) t3 WHERE ischild != 0 OR id = 1

查询id为268下的所有部门

SELECT id,name,parent_id FROM
lsblj_department ld,
(SELECT @id :=268) pd
WHERE (FIND_IN_SET( parent_id, @id ) > 0 AND @id := CONCAT( @id, ‘,’, id )) OR id = 268;

查询一个节点的所有父节点

SELECT T2.id, T2.name ,T2.parent_id FROM (
SELECT @id AS dept_id, (SELECT @id := parent_id FROM lsblj_department WHERE id = dept_id) AS parent_id
FROM (SELECT @id := 269) vars,lsblj_department ld ) T1
INNER JOIN lsblj_department T2
ON T1.dept_id = T2.id

你可能感兴趣的:(Mysql)