日期:2014-05-17  浏览次数:20488 次

下面要求的sql如何写
表Category
CategoryId Name
1           c1
2           c2
3           c3

表Product:
ProductId  Name
1           p1
2           p2
3           p3 

表Relationship
ProductId CategoryId
1          1
1          2
2          1
3          2
表Relationship用于描述产品与分类之间的关系,一个产品可以属于多个分类,一个分类有多个产品,现查询产品表要求返回下列结果,即多了一列,把分类名称串起来,显示到界面。
ProductId  Name  CategoryName
1           p1     c1,c2
2           p2     c2

想了很久无头绪,Please help。


------解决方案--------------------
应该是这样吧

ProductId  Name  CategoryName
1           p1     c1,c2
2           p2     c1
------解决方案--------------------

with Category(CategoryId,Name)as(
select 1,'c1' union all
select 2,'c2' union all
select 3,'c3'),
Product(ProductId,Name)as(
select 1,'p1' union all
select 2,'p2' union all
select 3,'p3'), 
Relationship(ProductId,CategoryId)as(
select 1,1 union all
select 1,2 union all
select 2,1 union all
select 3,2)
select distinct a.ProductId,a.Name, 
CategoryName=stuff((select ','+Category.Name from Product ,Relationship ,Category 
where Category.CategoryId=Relationship.CategoryId and Relationship.ProductId=b.ProductId
and Relationship.ProductId=b.ProductId and Product.Name=a.Name for xml path('')),1,1,'')
 from Product a,Relationship b,Category c
where a.ProductId=b.ProductId and b.CategoryId=c.CategoryId


------解决方案--------------------
create table category(categoryid int,name varchar(20));
insert into category 
select 1,'c1'
union all
select 2,'c2'
union all
select 3,'c3'
 
create table product(productid int,name varchar(20));

insert into product 
select 1,'p1'
union all
select 2,'p2'
union all
select 3,'p3'

create table  relationShip(productid int,categoryid int);

insert into relati