两张表联合查询 好久不写 悲剧了
有两张表:tab1 and tab2
tab1数据 tab2 数据
id name id name tab1
1 张三 1 作者 1,2,4
2 李四 2 文章 2,3
3 王五
4 赵六
要求生成的表:
1 作者 张三,李四,赵六
2 文章 李四,王五
[解决办法]
--> 测试数据:[ta]if object_id('[ta]') is not null drop table [ta]go create table [ta]([id] int,[name] varchar(4))insert [ta]select 1,'张三' union allselect 2,'李四' union allselect 3,'王五' union allselect 4,'赵六'--> 测试数据:[tb]if object_id('[tb]') is not null drop table [tb]go create table [tb]([id] int,[name] varchar(5))insert [tb]select 1,'1,2,4' union allselect 2,'2,3'--------------开始查询--------------------------go create function f_hb(@id varchar(10))returns varchar(1000)asbegin declare @str varchar(1000) set @str='' select @str=@str+','+[name] from [ta] where charindex(','+cast(id as varchar)+',',','+@id+',')>0 return stuff(@str,1,1,'')endgo select id,name=dbo.f_hb([name]) from [tb]--drop function f_hb--drop table ta,tb/*
[解决办法]
--> 测试数据:[ta]if object_id('[ta]') is not null drop table [ta]go create table [ta]([id] int,[name] varchar(4))insert [ta]select 1,'张三' union allselect 2,'李四' union allselect 3,'王五' union allselect 4,'赵六'--> 测试数据:[tb]if object_id('[tb]') is not null drop table [tb]go create table [tb]([id] int,[name] nvarchar(5),tab1 varchar(20))insert [tb]select 1,N'作者','1,2,4' union allselect 2,N'文章','2,3'select b.ID, b.name, stuff((select ','+[name] from ta a where CHARINDEX(','+ltrim(a.id)+',',','+b.tab1+',')>0 for XML path('')),1,1,'')from tb b
[解决办法]