SQL返回单个列中的所有相关行

时间:2012-07-26 10:32:27

标签: mysql sql relational-database

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

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

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

1 ==> 2,3

3 ==> 1,2

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

谢谢。

2 个答案:

答案 0 :(得分: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提供独特性)以及连接项之间的关系(也以两种方式)。

答案 1 :(得分: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