SQL,逗号分隔的条目通过许多表

时间:2011-05-25 21:25:47

标签: sql sql-server

假设我与三张桌子有着典型的多对多关系。

---------
--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。任何想法如何做到这一点?

感谢

2 个答案:

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

答案 1 :(得分:2)

MySQL具有group_concat功能。 Here's an article关于如何在SQL服务器上模拟