update语句!

[复制链接]
查看11 | 回复9 | 2006-5-9 18:02:12 | 显示全部楼层 |阅读模式
table1和table2的结构完全一样:
table1: myCode,myName
table2: myCode,myName
table1和table2的myCode字段的值一样,但是myName字段的值不一样!
把table2中myName的值更新到table1中,update语句该怎么写?
回复

使用道具 举报

千问 | 2006-5-9 18:02:12 | 显示全部楼层
table1和table2的结构完全一样:
table1: myCode,myName
table2: myCode,myName
table1和table2的myCode字段的值一样,但是myName字段的值不一样!
把table2中myName的值更新到table1中,update语句该怎么写?
分两步:
1 truncate table table1
2 insert into table1 select from table2;
回复

使用道具 举报

千问 | 2006-5-9 18:02:12 | 显示全部楼层
update table1 set myname = (select table2.myname from table2 where table1.mycode = table2.mycode)
where exists(select 1 from table2 t2 where table1.mycode = t2.mycode);
回复

使用道具 举报

千问 | 2006-5-9 18:02:12 | 显示全部楼层
最初由 lyra 发布
[B]table1和table2的结构完全一样:
table1: myCode,myName
table2: myCode,myName
table1和table2的myCode字段的值一样,但是myName字段的值不一样!
把table2中myName的值更新到table1中,update语句该怎么写?
分两步:
1 truncate table table1
2 insert into table1 select from table2; [/B]

兄弟,万一记录条数不同呢??
回复

使用道具 举报

千问 | 2006-5-9 18:02:12 | 显示全部楼层
请问:truncate table table1执行什么操作?
回复

使用道具 举报

千问 | 2006-5-9 18:02:12 | 显示全部楼层
最初由 xiaosi 发布
[B]请问:truncate table table1执行什么操作? [/B]

是DDL语句意思是截断表----删除记录重设高水位标记
回复

使用道具 举报

千问 | 2006-5-9 18:02:12 | 显示全部楼层
truncate table z执行清表操作;如果两个表的记录数原来就不一致,是不能这样做的.
看来还是用楼上的方法较好:
update table1 set myname = (select table2.myname from table2 where table1.mycode = table2.mycode)
where exists(select 1 from table2 t2 where table1.mycode = t2.mycode);
回复

使用道具 举报

千问 | 2006-5-9 18:02:12 | 显示全部楼层
不是说‘table1和table2的myCode字段的值一样’吗,
个人觉得用truncate+insert效率会高一点。
当然,如果原来的记录数不同就不能用这个方法了。
回复

使用道具 举报

千问 | 2006-5-9 18:02:12 | 显示全部楼层
update (select tabl1.name name1,table2.name from table1,tabl2 where table1.code=table2.code) set name1=name2
需要有主键或者唯一索引在code上
回复

使用道具 举报

千问 | 2006-5-9 18:02:12 | 显示全部楼层
如果table1只是为了对table2的更新,那么你就用truncate好了,这样table1表的数据就和table2表的数据就完全一致了,包括table2中删除的修改的!如果不仅仅对table2操作,你就用l楼上大哥的update方法!
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

主题

0

回帖

4882万

积分

论坛元老

Rank: 8Rank: 8

积分
48824836
热门排行