SQL 递归,根据产品和 parent 产品检索订单
SQL Recursion, Retrieve Orders based on Product and parent Product
我想要一个 SQL 查询 returns 'Orders' 基于关联的 'Product','Product.DepositId' 必须等于一个精确的整数值(例如 Product.DepositId = 1).
如果关联的 'Product.DepositId' 为空,则查询需要上升到 Product 阶梯,使用 'Product.ParentId' 获取 parent 'Product' 等等。
- A 'Product' parent 层次结构可以是 'N' tiers/layers。 (例如 Child -> ChildParent -> ChildParent -> 最终 Parent)
- 多个'Product'children可以关联到同一个Parent
- 只有最上面的 parent 'Product' 才会有 DepositId。因此,如果 'Product.ParentId' 为空,则 'Product.DepositId' 不会为空
- 'Order' 可以与 child 'Product' 或 parent 'Product' 相关联。 (Parents 也可以有订单。)
例如(为了简化示例,我使用了整数 ID 而不是唯一标识符)
产品
Id ParentId DepositId
1 NULL 10
2 NULL 20
3 1 NULL
4 2 NULL
5 1 NULL
6 3 NULL
订单
Id ProductId
1001 1
1002 2
1003 3
1004 4
1005 5
1006 6
DepositId = 10 的预期结果订单
OrderId ProductId
1001 1 --Because Product 1 DepositId = 10
1003 3 --Because Product 3 is child of Product 1
1005 5 --Because Product 5 is child of Product 1
1006 6 --Because Product 6 is child of Product 3 which in
turn is a child of Product 1
这需要递归 CTE。
;with rcte_products as (
select Id as ProductId, ParentId
, DepositId
, 0 as Lvl
, Id as BaseId
from Products
where DepositId = 10
union all
select t.Id, t.ParentId
, c.DepositId
, c.Lvl+1
, c.BaseId
from rcte_products c
join Products t on t.ParentId = c.ProductId
)
select
o.Id as OrderId
, o.ProductId
from rcte_products c
join Orders o
on o.ProductId = c.ProductId
order by o.Id;
OrderId
ProductId
1001
1
1003
3
1005
5
1006
6
演示 db<>fiddle here
我想要一个 SQL 查询 returns 'Orders' 基于关联的 'Product','Product.DepositId' 必须等于一个精确的整数值(例如 Product.DepositId = 1).
如果关联的 'Product.DepositId' 为空,则查询需要上升到 Product 阶梯,使用 'Product.ParentId' 获取 parent 'Product' 等等。
- A 'Product' parent 层次结构可以是 'N' tiers/layers。 (例如 Child -> ChildParent -> ChildParent -> 最终 Parent)
- 多个'Product'children可以关联到同一个Parent
- 只有最上面的 parent 'Product' 才会有 DepositId。因此,如果 'Product.ParentId' 为空,则 'Product.DepositId' 不会为空
- 'Order' 可以与 child 'Product' 或 parent 'Product' 相关联。 (Parents 也可以有订单。)
例如(为了简化示例,我使用了整数 ID 而不是唯一标识符)
产品
Id ParentId DepositId
1 NULL 10
2 NULL 20
3 1 NULL
4 2 NULL
5 1 NULL
6 3 NULL
订单
Id ProductId
1001 1
1002 2
1003 3
1004 4
1005 5
1006 6
DepositId = 10 的预期结果订单
OrderId ProductId
1001 1 --Because Product 1 DepositId = 10
1003 3 --Because Product 3 is child of Product 1
1005 5 --Because Product 5 is child of Product 1
1006 6 --Because Product 6 is child of Product 3 which in
turn is a child of Product 1
这需要递归 CTE。
;with rcte_products as ( select Id as ProductId, ParentId , DepositId , 0 as Lvl , Id as BaseId from Products where DepositId = 10 union all select t.Id, t.ParentId , c.DepositId , c.Lvl+1 , c.BaseId from rcte_products c join Products t on t.ParentId = c.ProductId ) select o.Id as OrderId , o.ProductId from rcte_products c join Orders o on o.ProductId = c.ProductId order by o.Id;
OrderId | ProductId |
---|---|
1001 | 1 |
1003 | 3 |
1005 | 5 |
1006 | 6 |
演示 db<>fiddle here