sql难题

icefireren 2006-01-13 04:18:05
表1:
序号 类型
1 1,2,3
2 4,3
3 5,2

表2:
序号 名称
1 A
2 B
3 C
4 C1
5 E

表1中类型对应于表2的序号。现在想知道如果要用sql语句得到如下结果该如何做?
要得到类似以下的数据行,该如何做?

序号 类型
1 A,B,C
2 C1,C
3 E,B
...全文
116 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
小辉 2006-01-13
  • 打赏
  • 举报
回复
--创建数据
create table tab1
( id int , type varchar(50))
insert into tab1
select 1 ,'1,111,2,3'
union select 2 ,'4,3'
union select 3 ,'5,2,1,11,111'

create table tab2
(id int , type varchar(10))
insert into tab2
select 1, 'A'
union select 2 ,'B'
union select 3 ,'C'
union select 4 ,'C1'
union select 5 ,'E'
union select 11 ,'s'
union select 111 ,'t'

--sql语句
update tab1 set type=','+type+','
declare @sql varchar(8000)
set @sql='type '
select @sql ='replace('+@sql+','','+cast(id as varchar)+','','','+type+','')' from tab2
set @sql = 'update tab1 set type=' + @sql
select @sql
exec(@sql)
update tab1 set type = substring(type ,2,len(type)-2)

--察看结果
select * from tab1
--删除测试数据
drop table tab1
drop table tab2



tab1

1 1,111,2,3
2 4,3
3 5,2,1,11,111

tab2

1 A
2 B
3 C
4 C1
5 E
11 s
111 t

--结果
1 A,t,B,C
2 C1,C
3 E,B,A,s,t

56,687

社区成员

发帖
与我相关
我的任务
社区描述
MySQL相关内容讨论专区
社区管理员
  • MySQL
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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