MySQL splicing table names recursively looking for child nodes and parent nodes

Source: Internet
Author: User
Tags stmt

BEGINDeclareLevint;--Query Parent   SetLev=1; Drop Table if existsTMP1; CREATE TABLETMP1 (IDVARCHAR( +), Wl_codevarchar( -), Parentcodevarchar( +), LEVVINT); --Splicing table names and parameters in a stitched manner   SET @sqlcmd =CONCAT ('INSERT tmp1 SELECT id,wl_code,parentcode,1 from', TableName,'WHERE wl_code=', Wlcode); --Statement      PREPAREstmt from @sqlcmd; --Execute SQL   EXECUTEstmt; --deallocate PREPARE stmt;    --SELECT Row_count ();   whileRow_count ()>0 DoSetLev=Lev+1; --stitching SQL and Parameters        SET @sqlcmd =CONCAT ('INSERT tmp1 SELECT T.id,t.wl_code,t.parentcode,', Lev,' from', TableName,'T join Tmp1 A on T.wl_code=a.parentcode and levv=', Lev-1); PREPAREstmt from @sqlcmd; EXECUTEstmt; End  while ; --SELECT DISTINCT id,wl_code,parentcode from TMP1;--Query sub-levelSETLev=1;--Query sub-level   Drop Table if existsTMP2; CREATE TABLETMP2 (IDVARCHAR( +), Wl_codevarchar( -), Parentcodevarchar( +), LEVVINT);SET @sqlcmd =CONCAT ('INSERT tmp2 SELECT id,wl_code,parentcode,1 from', TableName,'WHERE parentcode=', Wlcode); PREPAREstmt from @sqlcmd; EXECUTEstmt;  whileRow_count ()>0 DoSetLev=Lev+1; SET @sqlcmd =CONCAT ('INSERT tmp2 SELECT T.id,t.wl_code,t.parentcode,', Lev,' from', TableName,'T join TMP2 A on T.parentcode=a.wl_code and levv=', Lev-1); PREPAREstmt from @sqlcmd; EXECUTEstmt; End  while ;--SELECT DISTINCT id,wl_code,parentcode from TMP2;SELECT DISTINCTId,wl_code,parentcode fromTmp1UNION  All SELECT DISTINCTId,wl_code,parentcode fromTmp2Order  byID;END

MySQL splicing table names recursively looking for child nodes and parent nodes

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.