Update 多行数据(将一张表中某列的值更新到另外一张表中)

Oracle:
MERGE INTO PERSONTE
USING PERSON
ON (PERSONTE.name = PERSON.name)
WHEN MATCHED THEN
  UPDATE
     SET PERSONTE.sex = PERSON.sex
   WHERE PERSONTE.id = '1'
     AND PERSONTE.name IN ('q', 'w');

MS SqlServer:
UPDATE t2
   set t2.name = t1.name FROM t_test2 t2 INNER join t_test1 t1 ON t1.id = t2.id
 where t1.id = '3';

MySQL:
UPDATE test1 t2
INNER JOIN test t1 ON t1.id = t2.id
SET t2.NAME = t1.NAME
WHERE
    t1.id = '1';

--存在记录时,就更新(Update),不存在数据时,就插入(Insert)
MERGE INTO table_name alias1 
USING (table|view|sub_query) alias2
ON (join condition) 
WHEN MATCHED THEN 
    UPDATE table_name 
    SET col1 = col_val1, 
        col2     = col2_val 
WHEN NOT MATCHED THEN 
    INSERT (column_list) VALUES (column_values); 


--数据量小的时候可以使用子查询做两表关联操作;但数据量大的时候子查询效率太低(因为是单条比对)
--比如:
update person1 p1 set p1.p_name=(select p_name from person2 where p1.p_id=p2.p_id)  where p1.add_date>to_date('2014-09-01','yyyy-mm-dd')  

--而使用MERGE INTO...USING 作两表关联操作(增、删、改)就效率非常高
MERGE INTO person1 p1   
        USING (select p_id,p_name from person2 where use='952701' ) p2  
        ON ( p1.p_id=p2.p_id )      
        WHEN MATCHED THEN UPDATE SET p1.p_name = p2.p_name where p1.add_date>to_date('2014-09-01','yyyy-mm-dd')  
    commit;  



你可能感兴趣的:(Sql相关知识)