
我想要一個基于關聯的“產品”回傳“訂單”的 SQL 查詢,“Product.DepositId”必須等于一個精確的整數值(例如 Product.DepositId = 1)。
如果關聯的“Product.DepositId”為空,則查詢需要使用“Product.ParentId”等向上產品階梯獲取父“Product”。
- “產品”父層次結構可以有“N”層/層。(例如 Child -> ChildParent -> ChildParent -> Final Parent)
- 多個“產品”子項可以關聯到同一個父項
- 只有最頂層的父“產品”才會有一個存款 ID。因此,如果“Product.ParentId”為空,則“Product.DepositId”不會為空
- “訂單”可以與子“產品”或父“產品”相關聯。(父母也可以下訂單。)
例如(為了使示例簡單,我使用整數 id 而不是 uniqueidentifier)
產品
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
存款 ID = 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
uj5u.com熱心網友回復:
這需要遞回 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;
| 訂單編號 | 產品編號 |
|---|---|
| 1001 | 1 |
| 1003 | 3 |
| 1005 | 5 |
| 1006 | 6 |
關于db<>fiddle 的演示在這里
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/397725.html
標籤:sql sql-server 查询语句
下一篇:如何洗掉大表的嵌套回圈連接
