最近开发有一个需求,有一个商户表,表中数据如下图
每一个商户可以有上级商户,现在需求是一次性查询出 商户对应的所有下级,这里要用到递归查询,折腾了半天把sql弄出来了,记录一下
SELECT
B.MERCHANT_ID,
A. LEVEL
FROM
(
SELECT
@ids AS _ids,
(
SELECT
@ids := GROUP_CONCAT(MERCHANT_ID)
FROM
P_MERCHANT
WHERE
FIND_IN_SET(PARENT_MERCHANT_ID, @ids)
) AS cids,
@l := @l + 1 AS LEVEL
FROM
P_MERCHANT,
(SELECT @ids := 56, @l := 0) b
WHERE
@ids IS NOT NULL
) A,
P_MERCHANT B
WHERE
1 = 1
AND FIND_IN_SET(B.MERCHANT_ID, A._ids)
查询商户id = 56,层级为0时对应所有商户。
查询结果如下