简体   繁体   中英

possible normalization for a mysql query with joins

I made a query to get parents of a child till 6th parent . The query works fine . But i just wanted to know if there is a better scope to achieve the results via a better query cause in future if i want to get parent 7 and parent 8 i would need to modify this code and it will be long with increase in getting the parent ids . Also if anything can be possible via php that would be great too .

SELECT
    u.referred_by as parent_1,
    c1.referred_by as parent_2,
    c2.referred_by as parent_3,
    c3.referred_by as parent_4,
    c4.referred_by as parent_5,
    c5.referred_by as parent_6
FROM
    users u
LEFT JOIN users c1
    ON  c1.id=u.referred_by
LEFT JOIN users c2
    ON c2.id = c1.referred_by
LEFT JOIN users c3
    ON c3.id = c2.referred_by
LEFT JOIN users c4
    ON c4.id = c3.referred_by
LEFT JOIN users c5
    ON c5.id = c4.referred_by
WHERE u.id = 30

SQL FIDDLE

http://sqlfiddle.com/#!2/24694/1

You can use recursion for your works. The following is a simple recursion code that returns all ancestors but if you want to limit the number of parents that you want to get returns you can create a function with the following code and send argument 6(or 7) as parameter and check whether you has reach to you specific level of parents or not. hope it works. :)

with parents as (
   select id, referred_by
   from users 
   where id = 30
   union all
   select u.id, u.referred_by
   from users u
     join parents p on p.id = u.referred_by
) 
select *
from parents;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM