views:

31

answers:

0

Hi,

I'd need a MySQL query to transform my nested sets structure into XML. (no PHP)
The Problem is how to close all tags correct.

My method of resolution:
1) Find leaves
2) Make a "TAG"-string (group_concat) and make it shorter with level

This is running:

                                                      
A[01,16]
B[02,03]    C[04,13]    H[14,15]
            D[05,12]
            E[06,07]    F[08,11]
                        G[09,10]

<a><b></b><c><d><e></e><f><g></g></f></d></c><h></h></a>

This is NOT running (D is wrong):

                                 
A[01,16]
B[02,03]    C[04,15]
            D[05,14]
            E[06,11]    H[12,13]
            F[07,10]
            G[08,09]

SQL CODE:


SET @level:=0;
SELECT n.*,
    @level:=count(*)-1+(n.lft>1),
concat('<',n.name,'>',
IF(n.rgt-n.lft=1,
    group_concat(
        IF(
        p.rgt<n.rgt+@level,
        concat('</',p.name,'>'),
        '')
    ORDER BY p.rgt
SEPARATOR ''
    )
,'')
)
    FROM tree n,
         tree p
   WHERE n.lft BETWEEN p.lft AND p.rgt
GROUP BY n.id
ORDER BY n.lft;

thanks a lot for helping