4

我在 SQL Server 中看到了对递归的引用,但我使用的是 MySQL,并且要求结果在单个列中。如果我有一个关系表:

itemID1 | itemiD2
---------------
  1     |   2
  1     |   3
  4     |   5

如何在任一列中选择与单个 ID 相关的所有 ID?例如:

1 ==> 2,3

3 ==> 1,2

我尝试了自联接,但无法在单个列中获取所有相关 ID。如果对此有更好的架构,那么更改表还为时不晚。

谢谢你。

4

2 回答 2

5

请尝试以下查询:

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提供独特性)以及连接项目之间的关系(也可以两种方式)。

于 2012-07-26T11:21:19.003 回答
0

问题的部分答案。这不是解决递归而是传递性。

select itemID1, itemID2
from ((select itemID1, itemID2
       from t
      ) union all
      (select itemID2, itemID1
       from t
      )
     ) t
group by itemID1, itemID2

要将它们作为列表获取:

select itemID1, group_concat(distinct cast(itemID2 as varchar(32)) separator ',')
from ((select itemID1, itemID2
       from t
      ) union all
      (select itemID2, itemID1
       from t
      )
     ) t
group by itemID1, itemID2
于 2012-07-26T11:04:53.513 回答