mysql sql语句变量问题

SQL语句如下

SELECT ( @c:=s.id) as 'iid',
 (
    select f._id  from (SELECT @c as '_id',(select @c :=parent_id from sys_menu where id = @c) as 'pt'
     from sys_menu sy) f  where f.pt=0
 ) as 'parent'
 from   (select *  from sys_menu where id in(7,8,11)) s;
**
---结果中parent 应该为 1,2,3 ,返回的是1,1,1,不知道问题在哪里**


 #子语句运行结果
 set @c:=5;
 select f._id  from (SELECT @c as '_id',(select @c :=parent_id from sys_menu where id = @c) as 'pt'
    from sys_menu sy) f  where f.pt=0  
 ----结果为1

数据库中的数据如下

id parent_id
1 0
2 0
3 0
5 1
6 1
7 1
8 2
9 2
10 2
11 3
12 3
13 3
14 13
15 13
16 13

要显示子父级,你直接查表就可以显示,如果要显示递归的层级,那你直接用 with recursive temp就能查所有的啊

with recursive temp as (
select * from sys_menu p  
union all 
 select t.* from sys_menu t inner join temp t2 on t2.id = t.parent_id 
)
select *  from temp 

img

with recursive temp as (
select * from sys_menu p where p.id in (7,8,11) 
union all 
 select t.* from sys_menu t inner join temp t2 on t2.id = t.parent_id 
)
select *  from temp 

img

img


因为红框的sql只执行一次,按照结果的as parent,id =7的parent 是1,然后后面所有的结果集本质是 1 as parent。我猜你以为会是不断重新子sql动态返回parent——id把,然而只是第一次结果而已,所以你明白为啥都是1,1,1 了吗

1、不清楚题主想要实现什么业务逻辑,是递归找出指定ID的顶级parent_id吗?但似乎想要输出的又是1、2、3,而不是0、0、0……是只想要输出指定ID的parent_id吗? 直接用:

SELECT id as 'iid',parent_id as 'parent' from sys_menu where id in ( 7, 8, 11 );

就可以了啊?

在不支持递归函数的情况单纯用语句应该无法实现吧