sql >> Database teknologi >  >> RDS >> Mysql

Sådan finder du hierarkistien for en trærepræsentation

Du kan gå med en lagret procedure, som du har nævnt i dit spørgsmål, da indlejringen kan være op til 7 niveauer dyb.

Lagret procedure

CREATE PROCEDURE updatePath()
BEGIN
declare cnt, n int;
    select count(*) into n from foo where parent_id is null;
    update foo a, foo b set a.path = b.name where b.parent_id is null and a.parent_id = b.id;
    select count(*) into cnt from foo where path is null;
    while cnt > n do
        update foo a, foo b set a.path = concat(b.path, '/', b.name) where b.path is not null and a.parent_id = b.id;
        select count(*) into cnt from foo where path is null;
    end while;
END//
 

For at kontrollere den faktiske post har vi lige udskrevet de almindelige poster med nulværdi i stikolonnen

select * from foo
 

Resultater :

| ID | NAME | PARENT_ID | PATH | ------------------------------------------ | 1 | root1 | (null) | (null) | | 2 | child1 | 1 | (null) | | 3 | subchild1 | 2 | (null) | | 4 | child2 | 1 | (null) | | 5 | child3 | 1 | (null) | | 6 | subchild2 | 4 | (null) | | 7 | subsubchild1 | 6 | (null) |

Kald proceduren :

call updatepath
 

Resultat efter procedureudførelse :

select * from foo
 

Resultater :

| ID | NAME | PARENT_ID | PATH | ---------------------------------------------------------- | 1 | root1 | (null) | (null) | | 2 | child1 | 1 | root1 | | 3 | subchild1 | 2 | root1/child1 | | 4 | child2 | 1 | root1 | | 5 | child3 | 1 | root1 | | 6 | subchild2 | 4 | root1/child2 | | 7 | subsubchild1 | 6 | root1/child2/subchild2 |

SQLFIDDLE

Håber dette hjælper...



  1. Er det muligt at henvise til en kolonne som flere fremmednøgler?

  2. Hvordan indsætter man i samme tabel i MySQL?

  3. Indlejrede CASE-udsagn i MySQL

  4. pgmemcache vs Infinite Cache