簡體   English   中英

SQL在單個列中返回所有相關行

[英]SQL to return all related rows in a single column

我已經看到了在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提供獨特性)以及聯接項之間的關系(也可以兩種方式)。

該問題的部分答案。 這不是解決遞歸問題,而是傳遞性。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM