Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.8k views
in Technique[技术] by (71.8m points)

database - Mysql Chain Select Query

I have a database with a table which looks somewhat like this :

Root   |   Connector
  A    |      B
  B    |      C
  C    |      D
  D    |      E
  E    |      -

So i want to retrieve the chain for any given root till the connector is blank

For example : Chain of A means a->B->C->D->E whereas Chain of C means C->D->E

I am using mysql database.

Thanks in advance

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I just try with loop structure in Mysql and got success. Posting to share only--

CREATE PROCEDURE `root_connect`(IN init char(1),OUT str char(15))
BEGIN
    set @startChar:=(select connector from tableName where root = init);
    set @endloop := "no";
    set @fullchar:= @startChar;
    set @newchar:= "";  
    if (@startChar !="-" OR @startChar =null) then 
        WHILE (@endloop = "no") DO                  
            set @newchar :=(select connector from tableName where root = @startChar);       
            if(@newchar = '-') THEN
                set @endloop := "yes";
            else
                set @fullchar:= concat(@fullchar,"-",@newchar);
            end if;         
            set @startChar := @newchar;     
        END WHILE;
    end if;
        select @fullchar;
END

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...