POPMUISE
这是一个旧主题,但是由于我在另一个论坛中遇到了这个问题,所以我想在这里添加它。对于这种情况,我创建了一个存储过程,该存储过程经过硬编码以处理特定情况。当然这样做确实有一些缺点,因为并非所有用户都可以随意创建存储过程。考虑具有节点和子节点的下表:CREATE TABLE nodes ( parent INT, child INT);INSERT INTO nodes VALUES ( 5, 2), ( 5, 3), (18, 11), (18, 7), (17, 9), (17, 8), (26, 13), (26, 1), (26,12), (15, 10), (15, 5), (38, 15), (38, 17), (38, 6), (NULL, 38), (NULL, 26), (NULL, 18);使用此表,以下存储过程将计算一个由所提供节点的所有后代组成的结果集:delimiter $$CREATE PROCEDURE find_parts(seed INT)BEGIN -- Temporary storage DROP TABLE IF EXISTS _result; CREATE TEMPORARY TABLE _result (node INT PRIMARY KEY); -- Seeding INSERT INTO _result VALUES (seed); -- Iteration DROP TABLE IF EXISTS _tmp; CREATE TEMPORARY TABLE _tmp LIKE _result; REPEAT TRUNCATE TABLE _tmp; INSERT INTO _tmp SELECT child AS node FROM _result JOIN nodes ON node = parent; INSERT IGNORE INTO _result SELECT node FROM _tmp; UNTIL ROW_COUNT() = 0 END REPEAT; DROP TABLE _tmp; SELECT * FROM _result;END $$delimiter ;
守候你守候我
下面select列出了所有植物及其parentid最高4级(当然,您可以扩展该级):select id, name, parentid,(select parentid from tb_tree where id=t.parentid) parentid2,(select parentid from tb_tree where id=(select parentid from tb_tree where id=t.parentid)) parentid3,(select parentid from tb_tree where id=(select parentid from tb_tree where id=(select parentid from tb_tree where id=t.parentid))) parentid4 from tb_tree t然后您可以使用此查询获取最终结果。例如,您可以通过以下sql获取“水果”的所有子代:select id ,name from ( select id, name, parentid ,(select parentid from tb_tree where id=t.parentid) parentid2 ,(select parentid from tb_tree where id=(select parentid from tb_tree where id=t.parentid)) parentid3 ,(select parentid from tb_tree where id=(select parentid from tb_tree where id=(select parentid from tb_tree where id=t.parentid))) parentid4 from tb_tree t) ttwhere ifnull(parentid4,0)=1 or ifnull(parentid3,0)=1 or ifnull(parentid2,0)=1 or ifnull(parentid,0)=1