Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
SQL,通过多个表的逗号分隔的条目_Sql_Sql Server - Fatal编程技术网

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

SQL,通过多个表的逗号分隔的条目,sql,sql-server,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

假设我有三个表的典型多对多关系

---------
--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。有什么办法吗


谢谢

MySQL具有
group\u concat
功能。关于如何在SQL server上模拟这种情况

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
在这里测试它:

水果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

堆栈交换数据测试。。。很酷,我不知道那里有什么。一个关于解决方案的快速问题,我如何更改它以获得水果ID而不是水果名称?如果这不是公认的答案,那将是非常不公平的。