向B表插入A表有而B表无的数据;更新A表数据到B表

两个excel表 ,18日数据表和19日数据表. 并有两个要求:
 1. 18日表中的记录,如果在19日表中不存在,则将18日表中的此记录插入19日表
2. 18日表中标注了充值人的记录,用来替换19日表中的相同记录
分别把两个excel中的数据通过navicat中的"导入向导"导入到mysql中我新建的两张临时表temp3和temp4.
18日数据对应temp3;
19日数据对应temp4.

首先向temp4中插入在temp3中存在而在temp4不存在的数据

用了insert into select 

INSERT into temp4(type,exchange_no,balance,phone_count,exc_name,fromtable) SELECT 
type,exchange_no,balance,phone_count,exc_name,fromtable
from temp3 where exchange_no not in(
SELECT exchange_no from temp4
);

 这样完成了第一条要求.

第二个要求可以分以下几步 ;筛选两表中主键(exchange_no)相同的记录;再18日数据中记录人(exc_name)不为空的数据;把这部分数据更新到19表即temp4中.

扫描二维码关注公众号,回复: 1310359 查看本文章

也就是说需要要两表关联,同时把temp3中筛选后的数据更新到temp4中.

因为前边要求一已经往temp4插入过数据了,所以我把temp4的原始数据先备份成了temp4_copy,这样交互temp3后再更新到temp4中,

update temp4 t4 ,
(SELECT t3.exchange_no,t3.type,t3.balance,t3.phone_count,t3.exc_name,t3.fromtable from temp3 t3 , temp4_copy t4 where t3.exchange_no=t4.exchange_no and t3.exc_name!='') t5
set t4.type=t5.type,t4.balance=t5.balance,t4.phone_count=t5.phone_count,t4.exc_name=t5.exc_name,t4.fromtable=t5.fromtable
where t4.exchange_no=t5.exchange_no 

向一个表更新另一个表的数据 

UPDATE table t1, table2 t2  
    SET t1.field(需更新的字段) = t2.field(字段源)
    WHERE t1.id=t2.id
    AND ...

也可以用另一种更灵活的方法 即 join,这样你可以使用左,右联接以及内部联接.

UPDATE table t1  
    INNER JOIN table2 t2  
    ON t1.id=t2.id
    SET t1.field(需更新的字段) = t2.field(字段源)

猜你喜欢

转载自bluebing.iteye.com/blog/1833236