SQL,关于join的问题 [英] SQL, questions about join

查看:27
本文介绍了SQL,关于join的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 sql 2012 中有两个表:名称和具有结构的产品:

I have two tables in sql 2012: name and prod with structure:

name:id int increment,name1 nvarchar(50)

prod: id int increment, products nvarchar(50), id_name int

表的值为:

名称表:

Id   name1
1    pop
2    andi

产品表:

Id   products   id_name
1    coke       1
2    pizza      1
3    orange     2

我已经完成了这个查询:

I have done this query:

select name.name1, prod.product, prod.id_name
from name
join prod on name.id=prod.id_name

我怎样才能得到这个结果:

How can I obtain this result:

pop ->coke, pizza
andi->orange  

推荐答案

不幸的是,在 SQL Server 中没有简单的方法可以做到这一点.已知的解决方案是:

unfortunately, there's no easy way to do it in SQL Server. Known solutions are:

  • xml 技巧(见下文);
  • 使用变量累积数据(不适用于多组行,只能使用游标);
  • 自定义 CLR 聚合;

这里是 xml:

select
    n.name1,
    stuff(
        (
         select ', ' + p.product
         from prod as p
         where p.id_name = n.id
         for xml path(''),  type).value('.', 'nvarchar(max)')
    , 1, 2, '') as products
from name as n

sql 小提琴演示

这里的变量:

declare @product nvarchar(max), @id int

select @id = 1

select @product = isnull(@product + ', ', '') + product
from prod
where id_name = @id

select name1, @product as products
from name 
where id = @id

sql 小提琴演示

这篇关于SQL,关于join的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆