获取嵌套的相关产品mysql
我有两张表,可以相互查看相关产品获取嵌套的相关产品mysql,mysql,stored-procedures,Mysql,Stored Procedures,我有两张表,可以相互查看相关产品 product --------------------------------------------- product_id | Name | creation_date --------------------------------------------- 1 A 2017-03-11 11:30:13 2 B 2017-03-12 12:30:12 3
product
---------------------------------------------
product_id | Name | creation_date
---------------------------------------------
1 A 2017-03-11 11:30:13
2 B 2017-03-12 12:30:12
3 C 2017-03-13 13:30:45
4 D 2017-03-14 14:30:45
5 E 2017-03-15 15:30:45
product_related
---------------------------------------------
related_id | product_id | related_product_id
---------------------------------------------
1 1 2
2 2 5
3 3 1
4 4 3
我需要间接或直接获得所有相关产品
If @ProductID = 1, then I need Product ID's 2,3,4,5
If @ProductID = 2, then I need Product ID's 1,3,4,5
If @ProductID = 3, then I need Product ID's 1,2,4,5
If @ProductID = 4, then I need Product ID's 1,2,3,5
If @ProductID = 5, then I need Product ID's 1,2,3,4
如果需要更改与产品相关的表设计以提高执行性能,我可以 您已将其标记为php,因此我怀疑您还将遇到其他问题:) 您需要的是MySQL中的递归查询。我不是MySQL开发人员,但对于其他看到这篇文章并使用MS SQL的人来说,这非常简单。在MS SQL中,我们使用递归CTE(公共表表达式)来简化这种深度链接 请按照本文进行指导:
这真是一个糟糕的例子,不是吗?@草莓,是的,我接受要求很复杂,但这正是我需要的。我不介意我的相关结构是否需要任何更改