递归多对多表父对子对父

war*_*nks 7 t-sql sql-server recursion

我的老板给了我一张桌子.

Related_Items_Table

Item        | Accessory 
---------------------
TV          | Antennae 
TV          | Power Cord 
TV          | Remote 
Laptop      | Power Cord 
Laptop      | Carrying Case 
Camera      | Carrying Case 
Camera      | Lens 
iPod        | Headphones

描述我的老板想要结果的最佳方式是完成整个过程.

  1. 用户搜索电视.

  2. 电视被发现,电视配件是Antennae,Power Cord和Remote.

  3. 附件Antennae,Power Cord和Remote现在用于查找其他相关项目.电源线也是笔记本电脑的配件.Antennae和Remote不是任何其他物品的配件.

  4. 项目笔记本电脑现在用于查找该项目的配件,即电源线和便携包.

  5. 配件电源线和便携包现在用于查找其他相关项目.电源线没有找到新物品(我们已经知道电源线与电视和笔记本电脑有关).便携包也是相机的配件.

  6. 物品相机现在用于查找物品的配件,即携带箱和镜头.

  7. 配件携带箱和镜头现在用于查找其他相关物品.携带箱和镜头没有找到新物品(我们已经知道携带箱与笔记本电脑有关).

  8. 没有新项目可以继续搜索链.最终名单返回.

Final List 

Item        | Accessory 
---------------------
TV          | Antennae 
TV          | Power Cord 
TV          | Remote 
Laptop      | Power Cord 
Laptop      | Carrying Case 
Camera      | Carrying Case 
Camera      | Lens 

处理这个问题的最佳方法是什么?我不确定这个术语的正确性是什么,所以也许我在搜索中错过了它.任何建议表示赞赏.

Bri*_*ler 0

我会做这样的伪代码:

insert into Final_List
all the records that match the item in Related_Items_Table

WHILE 1=1
BEGIN
    Insert into Final List
    select NextLevel.*
    from Related_Items_Table
    join Related_Items_Table NextLevel
    on Related_Items_Table.Accessory = NextLevel.Item
    where the nextlevel.item and nextlevel.accesory not already in Final List
    if @@Rowcount = 0
        break
END
Run Code Online (Sandbox Code Playgroud)