求教各位大神。
查询两个表table A,table B,两个表通过A表user_id关联B表中的ID,其中A表中的user_id值有几个值,如:user_id="001,002,003",如何通过A表中的user_id关联到B表中的ID,并查询出A表所有字段及B表中的用户名?例
table A
id user_id            title    content
1   001,002,003   新闻  内容table  B
id    user_name  sex
001  张三            男
002  李四            男
003  王二           男
004  赵五           女查询结果为:
id          user_name              title      content
1      张三,李四,王二    新闻    内容
请问各位大神如何实现? 

解决方案 »

  1.   

    SELECT id
    ,STUFF((SELECT','+[user_name] FROM B T2
    WHERE ','+T1.[user_id]+','LIKE '%,'+CAST(T2.id AS VARCHAR(10))+',%'
    FOR XML PATH(''))
    ,1,1,'')[user_name]
    ,[title],[content]
    FROM A T1
      

  2.   

    大神这语句,在SQL里跑的出错,表名已经换过来了
      

  3.   

    select A.id,stuff((select ','+[user_name] from B where charindex(','+B.id+',',','+A.id+',')>0 for xml path('')),1,1,'') as [user_name], 
     title,[content]  from A
      

  4.   


    create table t1(id int, user_id nvarchar(max),title nvarchar(max),content nvarchar(max))
    create table t2(id nvarchar(max), user_name nvarchar(max),sex nvarchar(max))select * from t1
    select * from t2select a.id, (
    select user_name+','  from t2 b where a.user_id like '%'+b.id+'%' for xml path('')
    ) as user_name, title,contentfrom t1 a
      

  5.   

    select A.id,stuff((select ','+[user_name] from B where charindex(','+B.id+',',','+A.id+',')>0 for xml path('')),1,1,'') as [user_name], 
     title,[content]  from A