两表关联更新的语句为:
  update table1 set name=(select  from table2 where table1.id=table2.id) 
where exists (select 1 from table2 where table1.id=table2.id);
我一般在两表关联更新时是这样写的:
  update table1 set name=(select  from table2 where table1.id=table2.id) 
没有后面的where语句,不知道加了后面的条件语句以后有什么好处呢?
如果涉及多表更新呢?
  update table1 set 
       name1 = (select table2_field2 from table2 where table2.id = table1.id),
       name2 = (select table3.field3 from table3 where table3.id = table1.id)
  .....................
如果上面的语句要从多张表中取数据,然后更新多个字段时,该如何写?分开写,还是写成一句?
各有什么好处?

解决方案 »

  1.   

    要用一张表的多个字段更新另一张表的多个字段:
       update table1 set
         field1 = (select field1 from table2 where table2.id=table1.id),
         field2 = (select field2 from table2 where table2.id=table1.id),
         field3 = (select field3 from table2 where table2.id=table1.id),
         field4 = (select field4 from table2 where table2.id=table1.id)
    就只有上面的那种写法吗?有没有简洁一点的写法?另外此时加上where子句时有什么好处?
    where exists (select 1 from table2 where table1.id=table2.id);
      

  2.   

    多个字段更新可用如下方式:
    update table1 set field1,field2,field3..fieldn=(select field1,field2,field3..fieldn from table2 where table1.id=table2.id)
      

  3.   

    加条件语句可以避免对table1的全表扫描
      

  4.   

    1、加exists的目的是防止子查询找不到记录时update成空值。2、从多表更新只能如此。