表名:dw_region 把查询语句的#{id} 替换 子id
查询父id
select parent_ids from (
select
@id as id ,
(
SELECT
@id :=max(parent_id)
FROM
dw_region a
WHERE
a.id=@id
) AS parent_ids,
@l := @l + 1 AS `level`
FROM
dw_region dw_region,
(SELECT @id := (#{id}), @l := 0) b
)a where parent_ids is not null order by `level` desc
查询父name
SELECT GROUP_CONCAT(`name` ORDER BY id ) regionName FROM dw_region WHERE id in(
select parent_ids from (
select
@id as id ,
(
SELECT
@id :=max(parent_id)
FROM
dw_region a
WHERE
a.id=@id
) AS parent_ids,
@l := @l + 1 AS `level`
FROM
dw_region dw_region,
(SELECT @id := (#{id}), @l := 0) b
)a where parent_ids is not null )
根据id查询地区,has_children (Boolean)返回是否还有下级(儿子),parentIds 所有的父id(集合)
SELECT
id,
parent_id,
`name`,
address_code
CASE
WHEN has_children > 0 THEN
has_children ELSE 0
END has_children
FROM
dw_region dw_region
LEFT JOIN ( SELECT count( 0 ) AS has_children, parent_id AS child_id FROM dw_region GROUP BY parent_id ) dw_region2 ON dw_region2.child_id = dw_region.id
WHERE
dw_region.id = #{id}
返回格式:has_children (Boolean)返回是否还有下级(儿子)
parentIds: 所有的父id(集合)
根据父id查询子所有信息
SELECT
*
FROM
(
SELECT
t1.*,
IF
( FIND_IN_SET( parent_id, @pids ) > 0, @pids := CONCAT( @pids, ',', id ), '0' ) AS ischild
FROM
( SELECT * FROM 你的数据表 AS t ORDER BY t.id ASC ) t1,
( SELECT @pids := #{你的父id}) t2
) t3
WHERE
ischild != '0'
//我的数据表 是id和parent_id ,如果你的不是parent_id,也替换一下