mysql 递归查新

日期:2019-06-27 浏览:218次

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

表结构

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);

打印结果

转载:https://www.jianshu.com/p/64a22e77753f

没有评论

发表评论