mysql - Get last Left Child in binary tree in php

one text

Solution:

In MySQL 8.0, you can do this with a recursive query:

with recursive nodes as (
    select serial_id, upline, left pos, 1 lvl from customers where upline = 0
    union all
    select c.serial_id, c.upline, n.left + c.left, n.lvl + 1
    from nodes n
    inner join customers c on c.upline = n.serial_id
)
select *
from nodes
order by lvl desc, pos desc
limit 1

The query traverse the hierarchy tree from the root to the leafs, while keeping track of the level of each node and of how many "left" nodes were visited. You can then use this information to identify the deepest, most left node.

Source