I have a question about using recursive SQL in which I have the following table structure
Products can be in several groups (for clarity, I do not use int)
CREATE TABLE ProductGroups(ProductName nvarchar(50), GroupName nvarchar(50)) INSERT INTO ProductGroups(ProductName, GroupName) values ('Product 1', 'Group 1'), ('Product 1', 'Group 2'), ('Product 2', 'Group 1'), ('Product 2', 'Group 6'), ('Product 3', 'Group 7'), ('Product 3', 'Group 8'), ('Product 4', 'Group 6') +-----------+---------+ | Product | Group | +-----------+---------+ | Product 1 | Group 1 | | Product 1 | Group 2 | | Product 2 | Group 1 | | Product 2 | Group 6 | | Product 3 | Group 7 | | Product 3 | Group 8 | | Product 4 | Group 6 | +-----------+---------+
Now the question . I want to know all related products so if I transfer Product 1 , I need the following result
+-----------+---------+ | Product | Group | +-----------+---------+ | Product 1 | Group 1 | | Product 1 | Group 2 | | Product 2 | Group 1 | | Product 2 | Group 6 | | Product 4 | Group 6 | +-----------+---------+
So basically I want to know all the groups for product 1 first, and then for each group I want to know all the products, etc.
- Product 1 => Group 1, Group 2;
- Group 1 => Product 1, Product 2 (Group 1 and Product 1 already exist, so they should be avoided, otherwise they will go into infinity loop);
- Group 2 => Product 1 (already exists as described above);
- Product 2 => Group 1, Group 6 (Group 1 and Product 2 already exist)
- Group 6 => Product 4
source share