日期:2014-05-18  浏览次数:20691 次

一个比较复杂的查询,求教
三个表的关连查询
tab1.
id name
1 a
2 b

tab2.
id value1
1 a
1 NULL
1 b
2 c

tab3.
id value2
1 a
2 b
2 c

按照id做关联查询,但是需要把表1表2中具备相同id行的字段拼接成一个字符串,结果如下
id name value1 value2
1 a a,b a
2 b c b,c


------解决方案--------------------
SQL code

if object_id('[tab1]') is not null drop table [tab1]
go
create table [tab1]([id] int,[name] varchar(1))
insert [tab1]
select 1,'a' union all
select 2,'b'
go
if object_id('[tab2]') is not null drop table [tab2]
go
create table [tab2]([id] int,[value1] varchar(1))
insert [tab2]
select 1,'a' union all
select 1,null union all
select 1,'b' union all
select 2,'c'
go
if object_id('[tab3]') is not null drop table [tab3]
go
create table [tab3]([id] int,[value2] varchar(1))
insert [tab3]
select 1,'a' union all
select 2,'b' union all
select 2,'c'
go

select
  a.id,a.name,
  value1=stuff((select isnull(','+b.value1,'') from tab2 b where a.id=b.id for xml path('')),1,1,''),
  value2=stuff((select isnull(','+c.value2,'') from tab3 c where a.id=c.id for xml path('')),1,1,'')
from
  tab1 a
group by 
  a.id,a.name

/**
id          name value1                                             value2
----------- ---- -------------------------------------------------- -----------------------------
1           a    a,b                                                a
2           b    c                                                  b,c

(2 行受影响)

**/