1

Hello Experts i have node table which has nodeid and parentid columns and i trying to get list of all nodes in such a way that parent nodes are listed before child nodes .

In this sqlfiddle example i am not getting node id 20,21 as result

Query i have used is

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))
4
  • Can you provide your expected output? Commented Mar 13, 2019 at 9:46
  • 1
    side note: When it comes to hierarchical storage, parent row always comes before child. Meaning, parent_id cannot exist without it existing itself. In your case, how did you end up with (19, 'categor19', 2296) ? You are facing this issue because of a poor design. You may still achieve this with PHP as shown here. Commented Mar 13, 2019 at 9:52
  • 1 0 4 1 5 1 2296 4 19 2296 20 19 21 19 Commented Mar 13, 2019 at 9:52
  • Yes @vivek_23, yes that's how the data is , i need to create parent-node before child node , but query isn't returning in order that i am expecting. Isn't there a way in mysql to fix this. Commented Mar 13, 2019 at 9:56

1 Answer 1

0

Try the following query, I've tried it on sqlfiddle example you mentioned and it worked:

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);
Sign up to request clarification or add additional context in comments.

9 Comments

This doesn't work. It doesn't respect parent nodes are listed before child nodes.
order by becomes irrelevant actually. See the fiddle here. It doesn't yield as expected.
Try the edited version of the answer, I think this is what you wanted.
No. It doesn't work. Check the order of 19 and 2296.
Thanks @Abdo20293 , but as a result node 19 is coming after child nodes (20,21), whereas i am looking to get 1st parentnode then child node
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.