2011-05-25 22 views
2

假設我已經與三個表具有典型的多對多關係。SQL,通過許多表的逗號分隔條目

--------- 
--boxes-- 
--------- 
id name 
--------- 
1 Green Box 
2 Red Box 
3 Yellow Box 

---------- 
--fruits-- 
---------- 
id name 
---------- 
id name 
1 apple 
2 orange 

-------------- 
--fruitboxes-- 
-------------- 
boxID fruitID 
-------------- 
1  1 
1  2 
2  1 
2  2 
3  1 

我希望創建一個將導致

-------------------------- 
--------boxes view-------- 
-------------------------- 
id name   fruits 
-------------------------- 
1 Green Box  apple,orange 
2 Red Box   apple,orange 
3 Yellow Box  apple 

我使用的是MS SQL視圖。任何想法如何做到這一點?

感謝

回答

4
select 
    b.id, 
    b.name, 
    stuff((select ','+f.name 
     from fruits as f 
      inner join fruitboxes as fb 
      on f.id = fb.fruitID 
     where fb.boxID = b.id 
     for xml path(''), type).value('.', 'nvarchar(max)'), 1, 1, '') as Fruits 
from boxes as b 

測試它在這裏:http://data.stackexchange.com/stackoverflow/q/101351/concatenate-strings

水果的ID,而不是名稱

select 
    b.id, 
    b.name, 
    stuff((select ','+cast(fb.fruitID as varchar(10)) 
     from fruitboxes as fb 
     where fb.boxID = b.id 
     for xml path('')), 1, 1, '') as Fruits 
from boxes as b 
+2

堆棧交換數據測試...很漂亮flippin'酷,我不知道那裏。 – Daniel 2011-05-25 21:58:17

+0

關於解決方案的一個簡單問題,我如何更改它以獲取水果ID而不是水果名稱? – Daniel 2011-05-25 22:37:16

+0

如果這不是被接受的答案,那將是一個很大的不公正。 – 2011-05-26 03:45:43

2

的MySQL有group_concat功能。 Here's an article如何來模擬SQL服務器

+0

感謝迅速的回答,在看看現在 – Daniel 2011-05-25 21:29:25

+0

而一個downvote太。猜猜並不是每個人都很開心。 :) – GolezTrol 2011-05-25 21:33:32

+0

+1;漂亮的文章:) – 2011-05-25 21:44:42