Mysql
 SQL >> Datenbank >  >> RDS >> Mysql

Eine Elternhierarchie mit einer MySQL-Prozedur durchlaufen

Hier eine kleine Funktion, die ich zusammengestellt und an meiner Datenbank (MAMP) geprüft habe:

use mySchema; drop procedure if exists getParents; DELIMITER $$ CREATE PROCEDURE getParents (in_ID int) BEGIN DROP TEMPORARY TABLE IF EXISTS results; DROP TEMPORARY TABLE IF EXISTS temp2; DROP TEMPORARY TABLE IF EXISTS temp1; CREATE TEMPORARY TABLE temp1 AS select distinct ID, parentID from tasks where parentID = in_ID; create TEMPORARY table results AS Select ID, parentID from temp1; WHILE (select count(*) from temp1) DO create TEMPORARY table temp2 as select distinct ID, parentID from tasks where parentID in (select ID from temp1); insert into results select ID, parentID from temp2; drop TEMPORARY table if exists temp1; create TEMPORARY table temp1 AS select ID, parentID from temp2; drop TEMPORARY table if exists temp2; END WHILE; select * from results; DROP TEMPORARY TABLE IF EXISTS results; DROP TEMPORARY TABLE IF EXISTS temp1; END $$ DELIMITER ; 

Sie liefert alle Vorfahren bis zu beliebiger Tiefe, und Sie können results bei Bedarf um weitere Felder ergänzen. Aufruf:

call getParents(9148) 

Beachten Sie: Sie läuft von der angegebenen ID aus nach oben. Auf MySQL 8 erledigt eine rekursive WITH RECURSIVE-Klausel dasselbe in einer einzigen Anweisung, ganz ohne temporäre Tabellen.