现在的位置: 首页 > 综合 > 正文

关于两个表更新数据的问题(update)

2013年04月18日 ⁄ 综合 ⁄ 共 409字 ⁄ 字号 评论关闭

转摘

我现在有两张表.A与B
A的字段有id,name,pwd...
B的字段有userid,password
现在我想把A中pwd更新成B中的password(A中的id与B中的userid都是相对应于学生的ID),SQL语句应该怎么写呢??


update A
     set pwd = (select password from B where userid = A.id);

 


这样写逻辑有问题的,, 如果对应的记录在B表中不存在,,会被更新成null的..

1. update A set pwd = (select password from B where userid = A.id);
    where id in (select userid from B);

2. 如果B表的userid为主键的话,,可以使用关联更新..

update (
  select a.pwd pwd,b.password
  from A,B
  where a.id = b.userid
)
set pwd = password;

抱歉!评论已关闭.