user_id | name | parent_user_id |
0 | test-0 | nullmysql |
1 | test-1 | 0sql |
2 | test-2 | 0spa |
3 | test-3 | 1.net |
4 | test-4 | 3 |
如圖現有user表一張每條數據都與其餘數據存在關聯關係,如今有需求要查詢id=0和下面全部的數據,Sql以下:遞歸
SELECT
u.*
FROM
user u,
(
select
d.user_ids
from
(
select
@a := concat( @a, ',', b.user_id ) user_ids
from
user b,
(select @a := 0) c
where
find_in_set( b.parent_user_id, @a ) > 0
) d
order by
length( d.user_ids) desc
limit 1
) e
where
find_in_set( u.user_id, e.user_ids )ci
若是隻要id=0下面數據則能夠這樣寫,Sql以下:get
SELECT
u.*
FROM
user u,
(
select
substr(d.user_ids,length('0')+2) user_ids
from
(
select
@a := concat( @a, ',', b.user_id ) user_ids
from
user b,
(select @a := 0) c
where
find_in_set( b.parent_user_id, @a ) > 0
) d
order by
length( d.user_ids) desc
limit 1
) e
where
find_in_set( u.user_id, e.user_ids )it
以上就是所有內容,有什麼問題或者建議能夠下面留言table