I have a table like this
id , parent_id , name , leaf
1 , 0 ,parent 1 , 0
2 , 0 ,parent 2 , 0
3 , 1 ,child 1 , 0
4 , 3 ,child 2 , 1
5 , 2 ,child 3 , 0
6 , 5 ,child 4 , 1
7 , 0 ,child 5 , 1
And i want select leaves and it`s root name not parent name Something like below
id , name , root_name
4 , child 2 , parent 1
6 , child 4 , parent 2
7 , child 5 , null
Three may have many levels How can i do it just in MySQL with Stored Procedure ?