求一条更新语句

clisdodo 2015-08-26 12:24:15

/*表与字段说明
tb1 表1
tb2 表2
ls 序号
name 名字
bh 编号
mch 名称
*/
create table tb1(ls varchar(20),name varchar(20))
go
insert into tb1
select '001','五五' union all
select '001','田田' union all
select '001','七七' union all
select '002','方方' union all
select '003','红红' union all
select '003','花花' union all
select '004','牛牛' union all
select '004','丽丽'
select * from tb1
go

create table tb2(bh varchar(20),mch varchar(20))
go
insert into tb2
select '001','0' union all
select '002','0' union all
select '003','0' union all
select '004','0'
select * from tb2
go

/*现在需要一条更新语句,把tb2表中的mch字段更新成tb1表的name,
重点是提取tb1表中001这一组的第一条'五五'来更新,或者从001里面随机
提取一条更新.(随机或者只提第一条都可以)为方便演示更新效果,
下面的结果是提取每一组的第一条进行更新,更新完查询tb2效果如下

bh mch
---- -----
001 五五
002 方方
003 红红
004 牛牛
*/
...全文
68 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
卖水果的net 版主 2015-08-26
  • 打赏
  • 举报
回复

-- MAX 
update tb2 set mch = (select max(name) from tb1 where ls = bh)
go
-- 第一个
update tb2 set mch = (select top 1 name from tb1 where ls = bh)
go
-- 随机取
update tb2 set mch = (select top 1 name from tb1 where ls = bh order by NEWID())
go

34,594

社区成员

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

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