数据库
首页 > 数据库> > mysql – SQL – 递归查询

mysql – SQL – 递归查询

作者:互联网

我有以下带有示例数据的mysql表,如下所示:

 id    location            parentid
 1     UK                  0
 2     East Anglia         1
 3     Cambridgeshire      2
 4     Norfolk             2
 5     Suffolk             2 
 6     East Midlands       1
 7     Derbyshire          6
 8     Leicestershire      6 
 9     EU Countries        0
 10    Austria             9
 11    Belgium             9

我想生成一个查询,我可以按位置名称获取位置列表,但位置应包括任何父位置.例如

寻找民谣应该回归:

 id  location
 4   Norfolk, East Anglia, UK
 5   Suffolk, East Anglia, UK

搜索东方应返回:

id  location
2   East Anglia, UK
6   East Midlands, UK

搜索Bel应返回:

id  location
11  Belgium 

在上文中,我们排除了连续的欧盟国家

显然以下不起作用:

select c.id, CONCAT_WS(', ', c.location, p.location, pp.location) as location
from tbl_locations c
   outer left join tbl_locations p on p.id = c.parentid
   outer left join tbl_locations pp on pp.id = p.parentid
 where c.location like '%whatever%'

解决方法:

如果您只想要父位置,则可以通过自联接完成:

select c.id, c.location, p.id, p.location
from tbl_locations c
  outer left join tbl_locations p on p.id = c.parentid
where c.location like '%whatever%'

这可以扩展(通过外连接)到任意数量的级别,但查询将变长.例如.到三个级别:

select c.id, c.location, p.id, p.location, pp.id, pp.location
from tbl_locations c
  outer left join tbl_locations p on p.id = c.parentid
  outer left join tbl_locations pp on pp.id = p.parentid
where c.location like '%whatever%'

更一般的递归查询取决于RDBMS的详细信息.最简单的方法是使用公用表表达式(CTE).但MySQL不支持它们(至少,还没有).可以使用其他方法:Generating Depth based tree from Hierarchical Data in MySQL (no CTEs).

标签:recursive-query,sql,mysql
来源: https://codeday.me/bug/20190828/1753818.html