postgresql使用with recursive完成迭代查询

需求:

         查询某条记录的所有父亲节点,或者所有孩子节点。

表结构如下:(id是当前节点,super_cust_id是父节点,-1表示根节点)

 查询节点以及所有子节点sql语句:

<select id="queryNodesByParentId" resultMap="resultMap" parameterType="com.fh.iasp.app.cm.v2.custrel.pojo.BasCmCustomerRel">
		WITH RECURSIVE cust AS (
		SELECT
		r.*
		FROM
		bas_cm_customer_rel r
		WHERE
		r.status = '1'
		<if test="id != null">
			and r.id = #{id,jdbcType=BIGINT}
			UNION ALL
			SELECT
			rel.*
			FROM bas_cm_customer_rel rel
			JOIN cust AS B ON rel.super_cust_id = B. ID
		</if>
		) SELECT
		cust.*
		FROM cust;
	</select>

查询节点以及所有父节点sql语句:

<select id="queryNodesByParentId" resultMap="resultMap" parameterType="com.fh.iasp.app.cm.v2.custrel.pojo.BasCmCustomerRel">
		WITH RECURSIVE cust AS (
		SELECT
		r.*
		FROM
		bas_cm_customer_rel r
		WHERE
		r.status = '1'
		<if test="id != null">
			and r.id = #{id,jdbcType=BIGINT}
			UNION ALL
			SELECT
			rel.*
			FROM bas_cm_customer_rel rel
			JOIN cust AS B ON rel.ID = B.super_cust_id 
		</if>
		) SELECT
		cust.*
		FROM cust;
	</select>

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值