gpt4 book ai didi

mysql - @ Symbol - Mysql 中递归 SELECT 查询的解决方案?

转载 作者:行者123 更新时间:2023-11-29 02:28:42 25 4
gpt4 key购买 nike

有很多关于Mysql中递归SELECT查询的问题,但大多数答案是“There NO solution for Recursive SELECT query in Mysql”。

其实是有一定的解法的,想弄清楚,所以这道题是上一题的后续,可以在(how-to-do-the-recursive-select-query-in-mysql)找到

假设你有这张表:

col1 - col2 - col3
1 - a - 5
5 - d - 3
3 - k - 7
6 - o - 2
2 - 0 - 8

& 你想在 col1 中找到连接到值“1”的所有链接,即你想打印出来:

1 - a - 5
5 - d - 3
3 - k - 7

然后你可以使用这个简单的查询:

select col1, col2, @pv:=col3 as 'col3' from table1
join
(select @pv:=1)tmp
where col1=@pv

好的,但是,如果您的表有 2 条记录在 col1 中包含“1”,而 2 条记录在 col1 中包含“3”,例如:

col1 - col2 - col3
1 - a - 5
1 - m - 9
5 - d - 3
3 - k - 7
6 - o - 2
3 - v - 10
2 - 0 - 8

然后,当用户在col1中搜索“1”时,它应该显示所有连接到2个“1”的链接,即它应该显示这样的预期结果:

col1 - col2 - col3
1 - a - 5
1 - m - 9
5 - d - 3
3 - k - 7
3 - v - 10

所以,我的问题是我们如何修改上面的查询,以便它显示上面预期结果中的所有链接?

编辑:@戈登,但是如果我们省略 select distinct col1, col2 from 那么这个查询就有意义了,你能解决这个问题吗(因为 childID 增加了,所以我们可以订购 table1 ):

select col1, col2,
@pv:=(case when find_in_set(col3, @pv) then @pv else concat(@pv, ',', col3)
end) as 'col3'
from (select * from table1 order by col1) tb1 join
(select @pv:='1') tmp
on find_in_set(col1, @pv) > 0

在这种情况下,我们不用担心顺序,例如,如果这是数据:

col1 - col2 - col3
4 - a - 5
1 - d - 2
1 - k - 4
2 - o - 3
6 - k - 8
8 - o - 9

输出将是:

col1 - col2 - col3
1 - d - 1,2
1 - k - 1,2,4
2 - o - 1,2,4,3

所以我们得到这个结果 1,2,4,3 对吗?如果 col1 在 1,2,4,3 中,我们只选择所有记录。那么我们就可以得到最终的预期结果。

如果是这样,你能想到任何排除我刚才提到的解决方案的特殊情况吗?

最佳答案

我一直在想这样的事情是否可行:

select distinct col1, col2
from (select col1, col2,
@pv:=(case when find_in_set(col3, @pv) then @pv else concat(@pv, ',', col3)
end) as 'col3'
from table1 join
(select @pv:='1') tmp
on find_in_set(col1, @pv) > 0
) t

像这样的东西应该适用于小数据集。但是,将所有 id 放在一个字符串中的想法受限于一个字符串的容量。

关于mysql - @ Symbol - Mysql 中递归 SELECT 查询的解决方案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16542013/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com