专家您好,我有一个具有nodeid和parentid列的节点表,并且我试图以这样的方式获取所有节点的列表:父节点在子节点之前列出。
在此sqlfiddle示例中,我没有得到节点ID 20,21作为结果
我使用的查询是
select nodeid,parentid from
(select * from node
order by parentid, nodeid) channel_sorted,
(select @pv := '0') initialisation
where find_in_set(parentid, @pv) and length(@pv := concat(@pv, ',', nodeid))
答案 0 :(得分:0)
尝试以下查询,我已经在您提到的sqlfiddle示例中对其进行了尝试,并且有效:
SET @position := 0;
select nodeid,parentid from
(select nodeid,node.parentid from
(select distinct parentid,(@position := @position + 1) s
from node) as t inner join node on t.parentid=node.nodeid
order by s) as f
union
select nodeid,parentid
from node
where nodeid not in (select parentid from node);