我在 SQL Server 中看到过对递归的引用,但我使用的是 MySQL 并要求结果位于单个列中。如果我有一个关系表:
itemID1 | itemiD2
---------------
1 | 2
1 | 3
4 | 5
如何在任一列中选择与单个 ID 相关的所有 ID?例如:
1 ==> 2,3
3 ==> 1,2
我试过自联接,但无法在单个列中获取所有相关 ID。如果对此有更好的架构,更改表格还为时不晚。
谢谢。
最佳答案
请尝试这个查询:
select
itemID1, group_concat(cast(itemID2 as char) separator ',')
from
(
select itemID1, itemID2 from st where itemID1 = :ID
union
select itemID2, itemID1 from st where itemID2 = :ID
union
select s1.itemID2, s2.itemID2 from st as s1 inner join st as s2 on s1.itemID1 = s2.itemID1
where s1.itemID2 = :ID
union
select s1.itemID1, s2.itemID1 from st as s1 inner join st as s2 on s1.itemID2 = s2.itemID2
where s1.itemID1 = :ID
) as subquery
where itemID1 <> itemID2
group by itemID1
通过这种方式,您可以通过两种方式选择关系(union
提供独特性)以及连接项之间的关系(也可以通过两种方式)。
关于mysql - SQL返回单个列中的所有相关行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11667424/