如何实现下面的查询: 比如:12,1125,45,87 对应的字段 aaa,srw,sdfw,dge

蝈蝈俊 2003-05-10 01:11:40
Table1 结构:
ids nvarchar(100)
比如有这样的数据:
1,20,3
5,6,7
8
142,58

Table2 结构:
id int
name nvarchar(50)
比如有如下的数据:
1 aaa
2 ddfg
3 yrt
4 deeg
58 weew

其中Table1 中字段ids 记录的是 类似下面的字符串: 1,2,3,4 每个数字对应Table2 表中的一条记录。

我如何实现下面的查询结果:
1,20,3 aaa,wewe,yrt
5,6,7 www,eeer,eret

...全文
32 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
蝈蝈俊 2003-06-26
  • 打赏
  • 举报
回复
test
pengdali 2003-05-11
  • 打赏
  • 举报
回复
并运算
select c1,c2 from t1
union all
select c1,c2 from t2

差:
c1-c2:

select * from t1 where not exists(select 1 from t2 where t1.c1=t2.c1 and t1.c2=t2.c2)

c2-c1:

select * from t2 where not exists(select 1 from t1 where t1.c1=t2.c1 and t1.c2=t2.c2)

交:
select * from t1 where exists(select 1 from t2 where t1.c1=t2.c1 and t1.c2=t2.c2)


除:
create table #1(A char(1),B char(1),C char(1),D char(1))
insert #1 values('a','b','c','d')
insert #1 values('a','b','e','f')
insert #1 values('b','c','e','f')
insert #1 values('e','d','c','d')
insert #1 values('e','d','e','f')
insert #1 values('a','b','d','e')

create table #2 (A char(1),B char(1))
insert #2 values('c','d')
insert #2 values('e','f')

select a,b from #1 bb where exists(select 1 from (select distinct #1.a,#1.b,#2.a c,#2.b d from #1,#2) aa where aa.a=bb.a and aa.b=bb.b and aa.c=bb.c and aa.d=bb.d) group by a,b having count(*)>1




drop table #1
drop table #2
lynx1111 2003-05-10
  • 打赏
  • 举报
回复
高手之间的对话!
听听!
蝈蝈俊 2003-05-10
  • 打赏
  • 举报
回复
非常感谢,这个问题已经解决了,帮我再看一个问题吧:

http://expert.csdn.net/Expert/topic/1764/1764840.xml

thanks
pengdali 2003-05-10
  • 打赏
  • 举报
回复
create table Table1(ids nvarchar(100))

insert table1 values('1,20,3')
insert table1 values('5,6,7')
insert table1 values('8')
insert table1 values('142,58')


create table Table2(id int,name nvarchar(50))
insert Table2 values(1, 'aaa')
insert Table2 values(2 , 'ddfg')
insert Table2 values(3 , 'yrt')
insert Table2 values(4 ,'deeg')
insert Table2 values(58 ,'weew')


go

create function getstr(@a nvarchar(100))
returns nvarchar(4000)
as
begin
declare @str nvarchar(4000)
set @str=N''
select @str=@str+N','+rtrim(name) from Table2 where ','+@a+',' like '%,'+cast(id as varchar(10))+',%'
if len(@str)<>0 set @str=right(@str,len(@str)-1)
return @str
end
go

--调用
select ids,dbo.getstr(ids) from table1
pengdali 2003-05-10
  • 打赏
  • 举报
回复
1,20,3 aaa,wewe,yrt <<===按你题目上的你的结果是错的吧!
5,6,7 www,eeer,eret

34,590

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧