高效批量更新 sql 字段的值(从一个表向另一个表更新)

时间:2022-10-06 15:53:06

里给出一种更高效、简洁的做法,批量更新SQL ,一句SQL就可以替代麻烦的循环过程,有MS SQLServer、Oracle、DB2下的写法
--关键点:t4和t1是同一个table,primary key肯定也是同一个,
--并以它进行关联,这样在 select语句里即可引用到要update的表的fields 
UPDATE Table1 AS t1 
SET (Field1,Field2) = (SELECT Field21, Field22 
                       FROM Table2 t2 
                            INNER JOIN Table3 t3 
                                 ON t3.Field31 = t2.Field23 
                            INNER JOIN Table4 t4 
                                 ON t3.Field32 = t4.Filed41 
                       WHERE t2.Field24 >= '' 
                                      AND t1.fId = t4.fId); 
----------------------------MS SQLServer --------------------------------------

UPDATE t1 
SET Field1 = Field21, Field2 = Field22 
FROM Table2 t2 
         INNER JOIN Table3 t3 
              ON t3.Field31 = t2.Field23 
         INNER JOIN Table4 t4 
              ON t3.Field32 = t4.Filed41 
WHERE ((t2.Field24 >= '') 
                  AND t1.fId = t4.fId); 
----------------------------Oracle --------------------------------------------

UPDATE Table1 t1 
SET (Field1,Field2) = (SELECT Field21, Field22 
                       FROM Table2 t2 
                            INNER JOIN Table3 t3 
                                 ON t3.Field31 = t2.Field23 
                            INNER JOIN Table4 t4 
                                 ON t3.Field32 = t4.Filed41 
                       WHERE ((t2.Field24 >= '') 
                                 AND t1.fId = t4.fId)) 
WHERE EXISTS (SELECT Field21, Field22 
              FROM Table2 t2 
                   INNER JOIN Table3 t3 
                        ON t3.Field31 = t2.Field23 
                   INNER JOIN Table4 t4 
                        ON t3.Field32 = t4.Filed41 
              WHERE ((t2.Field24 >= '') 
                               AND t1.fId = t4.fId)); 
---------------------------------DB2 ------------------------------------------

UPDATE Table1 AS t1 
SET (Field1,Field2) = (SELECT Field21, Field22 
                       FROM Table2 t2 
                            INNER JOIN Table3 t3 
                                 ON t3.Field31 = t2.Field23 
                            INNER JOIN Table4 t4 
                                 ON t3.Field32 = t4.Filed41 
                       WHERE ((t2.Field24 >= '') 
                                         AND t1.fId = t4.fId)) 
WHERE EXISTS (SELECT Field21, Field22 
              FROM Table2 t2 
                   INNER JOIN Table3 t3 
                        ON t3.Field31 = t2.Field23 
                   INNER JOIN Table4 t4 
                        ON t3.Field32 = t4.Filed41 
              WHERE ((t2.Field24 >= '') 
                                AND t1.fId = t4.fId));