在表中一定要有id和pid,这样才能使用该sql。
根据pid查询出其下的所有子集(比如,子集的子集的子集…)全部查询出来。
SELECT GROUP_CONCAT(id) AS all_sub_ids
FROM (
SELECT * FROM (
SELECT id,parent_id
FROM 表
ORDER BY parent_id, id
) org_query,
(SELECT @id := 此处填写需要查询的PID) initialisation
WHERE FIND_IN_SET(parent_id, @id) > 0
AND @id := CONCAT(@id, ',', id)
) sub_query;
这样就把pid下所有的子集全部查询出来,但是只在一列输出,用,分割开来:
根据pid查询出其下的所有子集(比如,子集的子集的子集…)全部查询出来,但是需要作为集合列表展示,一个id作为一条数据:
这个sql使用时,需要区别mysql版本是5还是8!
5.7版本如下:
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(all_sub_ids, ',', rn), ',', -1) AS id_list
FROM (
SELECT GROUP_CONCAT(id) AS all_sub_ids,
ANY_VALUE(LENGTH(GROUP_CONCAT(id SEPARATOR ',')) - LENGTH(REPLACE(GROUP_CONCAT(id SEPARATOR ','), ',', '')) + 1) AS c,
@rownum := @rownum + 1 AS rn
FROM (
SELECT * FROM (
SELECT id,parent_id
FROM 表
ORDER BY parent_id, id
) org_query,
(SELECT @id := 此处填写需要查询的PID) initialisation
WHERE FIND_IN_SET(parent_id, @id) > 0
AND @id := CONCAT(@id, ',', id)
) sub_query,
(SELECT @rownum := 0) r
GROUP BY rn
) ids;
8.0版本如下:
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(all_sub_ids, ',', rn), ',', -1) AS id_list, c
FROM (
SELECT GROUP_CONCAT(id) AS all_sub_ids,
LENGTH(GROUP_CONCAT(id SEPARATOR ',')) - LENGTH(REPLACE(GROUP_CONCAT(id SEPARATOR ','), ',', '')) + 1 AS c,
@rownum := @rownum + 1 AS rn
FROM (
SELECT * FROM (
SELECT id, parent_id
FROM 表
ORDER BY parent_id, id
) org_query,
(SELECT @id := 此处填写需要查询的PID) initialization
WHERE FIND_IN_SET(parent_id, @id) > 0
AND @id := CONCAT(@id, ',', id)
) sub_query,
(SELECT @rownum := 0) r
GROUP BY rn, c
) ids;
简化版:
上面的sql其实就是脱裤子放屁,哈哈哈哈
SELECT id
FROM (
SELECT id,parent_id
FROM process_bim_data
ORDER BY parent_id, id
) org_query,
(SELECT @id := 452) initialisation
WHERE FIND_IN_SET(parent_id, @id) > 0
AND @id := CONCAT(@id, ',', id)