简体   繁体   中英

SQL to return all related rows in a single column

I've seen references to recursion in SQL Server, but I'm using MySQL and require the result to be in a single column. If I have a table of relationships:

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

How do I select all IDs related to a single ID in either column? For example:

1 ==> 2,3

3 ==> 1,2

I tried self joins, but can't get all related IDs in a single column. If there's a better schema for this it's not too late to change the table.

Thank you.

Please try this query:

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

This way you select relation in both ways ( union provides distinctiveness) as well as relation between joined items (also in both ways).

A partial answer to the question. this doesn't address the recursion but rather the transitivity.

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

To get them as a list:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM