批量更新问题(也许不准确)。

fanherong 2008-04-03 03:45:18
问题是 这样的
有两个表table1,table2
table1中的一些记录的一个字段要更新为table2中某条记录的一个字段值。
table1,table2有一个关联的 字段,更新的条件就是该字段相等。
如下:
table1:
id groupid ,groupname
1 0001, name1
2 0002, name1
3 0003, name1
4 0004, name1

5 0005, name2
6 0006, name2
7 0007, name2
8 0008, name2

table2:
groupid ,groupname
34, name1
45, name2

要等到更新后的table1如下:
//groupname相同就是更新的条件
table1:
id groupid ,groupname
1 34, name1
2 34, name1
3 34, name1
4 34, name1

5 45, name2
6 45, name2
7 45, name2
8 45, name2


请问我该怎么写sql?
...全文
110 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
Limpire 2008-04-05
  • 打赏
  • 举报
回复
table2:
groupid ,groupname
34, name1
45, name2

如果是1对1,有没有 top 1 都一样,如果是多对1,如:

groupid ,groupname
34, name1
35, name1
45, name2

是更新为34,还是35呢,Top 1 或许(因为 Top 1 具有不确定性)能更新为34。

fxwlei3245 2008-04-04
  • 打赏
  • 举报
回复
5楼正确,不过加个top 1好点.

update t1 set groupid = (select top 1 groupid from t2 where t2.groupname = t1.groupname)


我是新手,想请教一下,为什么要加一个TOP 1,谢谢
yyunffu 2008-04-03
  • 打赏
  • 举报
回复
dawugui 多谢!
kaikai_kk 2008-04-03
  • 打赏
  • 举报
回复

update table1 set groupid =b.groupid
from table1 a,table2 b
where a.groupname=b.groupname
dawugui 2008-04-03
  • 打赏
  • 举报
回复
5楼正确,不过加个top 1好点.

update t1 set groupid = (select top 1 groupid from t2 where t2.groupname = t1.groupname)
yyunffu 2008-04-03
  • 打赏
  • 举报
回复
id groupid groupname
----------- ------- ----------
1 34 name1
2 34 name1
3 34 name1
4 34 name1
5 45 name2
6 45 name2
7 45 name2
8 45 name2
yyunffu 2008-04-03
  • 打赏
  • 举报
回复
create table t1(id int, groupid varchar(5), groupname varchar(10))
insert into t1 select 1,'0001','name1'
union all select 2,'0002','name1'
union all select 3,'0003','name1'
union all select 4,'0004','name1'
union all select 5,'0005','name2'
union all select 6,'0006','name2'
union all select 7,'0007','name2'
union all select 8,'0008','name2'

select * from t1

create table t2(groupid varchar(5), groupname varchar(8))
insert into t2 select '34','name1'
union all select '45','name2'

select * from t2

update t1
set groupid = (select groupid from t2 where t2.groupname = t1.groupname)

select * from t1

drop table t1,t2
sweetweiwei 2008-04-03
  • 打赏
  • 举报
回复
update table1
set table1.groupid = table2.groupid
from table1
inner join table2 on table1.groupname = table2.groupname
areswang 2008-04-03
  • 打赏
  • 举报
回复
update table1 set groupid =b.groupid
from table1 a,table2 b
where a.groupname=b.groupname
-狙击手- 2008-04-03
  • 打赏
  • 举报
回复
update a
set groupid = b.groupid
from table1 a ,table2 b
where a.groupname = b.groupname
ojuju10 2008-04-03
  • 打赏
  • 举报
回复

update a set a.groupid=b.groupid from table1 a,table2 b
where a.groupname=b.groupname

34,591

社区成员

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

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