1.
table1                     table2
id name                    nameid     data
1  test                    1           1234567
2  aaa                     4           test1234
3  bbb
4  ccc如用用sql查询得到如下结果
id name data
1  test 1234567
2  aaa   NULL
3  bbb   NULL
4  ccc   test1234
SQL查询语句如何写select table1.*,table2.data from table1 left join table2 on table1.id=table2.nameid2.
table1
id  name
1   aaa
2   bbb
3   ccc
4   eee
.....
用SQL如何查询出的值为name的连接 如结果为
name
aaa,bbb,ccc,...declare @a varchar(8000)
set @a=''
select @a=@a+','+name from table1
select right(@a,len(@a)-1)

解决方案 »

  1.   

    select A.id, A.name, B.data from table1 as A 
     left join table2 as B on A.id = B.nameid
      

  2.   

    declare @a varchar(8000)
    declare @i int
    declare @m int
    set @i = 1
    select @m = max(id) from table1
    set @a=''
    while @i <= @m
    begin
     select @a = @a+','+name from table1 where id = @i
     set @i = @i + 1
    end
    select @a
      

  3.   

    1:
    select a.*,b.data from table1 left join table2 b on a.id=b.nameid
    2:
    declare @a varchar(8000)
    select @a=''
    select @a=@a+name from table
    select left(@a,len(@a)-1) as name