MySQL中A表數據UPDATE到B表
場景1:表B:id,name,code三個字段均有值;表A :id,name,code 其中id,name有值並且與表B相對應,code值爲null。現在將B表中的code值更新到A表中。
方法1:id不能有重複:
update t_a a set a.code=(select code from t_b b where b.id=a.id )
方法2:適合少量數據
update t_a a inner join (select code from t_b ) b set a.code=b.code;
場景2:表B:id,name,code,detail四個字段均有值;表A id,name,code,detail其中id,name有值並且與表B相對應,code,detail值爲null。現在將B表中的code和detail值更新到A表中。
方法1:
update t_a a set
a.code=(select code from t_b b where b.id=a.id ),
a.detail=(select detail from t_b b where b.id=a.id );
方法2:
update t_a a inner join (select code, detail from t_b ) b set a.code=b.code, a.detail=b.detail;
場景3:將表B中數據全部更新到A中,存在即更新code字段,不存在便插入新記錄
方法1:
insert into t_a (id, name, code) select id, name, code from t_b ON DUPLICATE KEY UPDATE code=VALUES(code);
存在即更新關鍵字:ON DUPLICATE KEY UPDATE