显示具有包含多个值的列的值

时间:2018-11-26 17:14:16

标签: sql tsql

我有很多产品的配方-多对多关系,并且在视图表中,我想像这样一行显示配方和产品:

create view AllRecipe as
select Recipe.RecipeName,Recipe.Picture,Recipe.Scoring,Recipe.Preparation,Product.ProductName
from Recipe join ProductsRecipe on Recipe.Id=ProductsRecipe.RecipeId
join Product on ProductsRecipe.Product=Product.Id

和结果:

___ RecipeName   Picture   Scoring   Preparation   ProductName
1   salad        null      7         Cut and mix   cucumber
2   salad        null      7         cut and mix   tomato 

但我想要

___ RecipeName   Picture   Scoring   Preparation   ProductName
1   salad        null      7         Cut and mix   cucumber tomato

我该怎么做?

1 个答案:

答案 0 :(得分:0)

这就是答案!!谢谢大家!

ans来自这里:simulating-group-concat-mysql-function-in-microsoft-sql-server-2005

非常有帮助!

SELECT Recipe.RecipeName,Recipe.Picture,Recipe.Scoring,Recipe.Preparation, STUFF(
             (SELECT ',' + ProductName
              from Recipe
    join ProductsRecipe on Recipe.Id=ProductsRecipe.RecipeId
    join Product on ProductsRecipe.Product=Product.Id
              FOR XML PATH (''))
             , 1, 1, '')
    from Recipe
    join ProductsRecipe on Recipe.Id=ProductsRecipe.RecipeId
    join Product on ProductsRecipe.Product=Product.Id
group by Recipe.RecipeName,Recipe.Picture,Recipe.Scoring,Recipe.Preparation