mysql 递归查询

应用场景:根据地级市的id向上进行uid递归查询

表结构

mysql 递归查询_第1张图片

php代码

$id = $this->request->param(‘id’);
if (empty($id)){
return warn(‘请求错误 ‘);
}
$sql = “SELECT id, name, citycode, parent_id FROM ( SELECT @r AS _id, ( SELECT @r := parent_id FROM db_areas WHERE id = _id ) AS parent_ids, @l := @l + 1 AS lvl FROM (SELECT @r := $id, @l := 0) vars, db_areas h WHERE @r <> 0 ) T1 JOIN db_areas T2 ON T1._id = T2.id ORDER BY id;”;
$data = Db::query($sql);

打印结果
mysql 递归查询_第2张图片
转载:https://www.jianshu.com/p/64a22e77753f

文章链接:mysql 递归查询

个人博客:www.liusongs.com

你可能感兴趣的:(mysql,ThinkPHP5)