一:需求
A表和B表的表結構相同,A表是歷史表,B表是增量數據表;想要根據關聯條件更新A表中的數據。
二:表結構
CREATE TABLE `A` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`bid` bigint(20) NOT NULL ,
`sid` bigint(20) NOT NULL ,
`grid` bigint(20) NOT NULL ,
`age` bigint(20) NOT NULL ,
`pv` bigint(20) NOT NULL ,
`uv` bigint(20) NOT NULL ,
`pay_count` bigint(20) NOT NULL,
`charge_amount` bigint(20) NOT NULL ,
`last_pay_count` bigint(20) NOT NULL ,
`last_charge_amount` bigint(20) NOT NULL ,
`ftime` bigint(20) NOT NULL ,
`dtime` bigint(20) NOT NULL DEFAULT '0' COMMENT '詳細時間(yyyyMMddHH)'
PRIMARY KEY (`id`,`ftime`),
KEY `IX_FTIME` (`ftime`) USING BTREE,
KEY `IX_HTIME` (`htime`) USING BTREE,
KEY `IX_DTIME` (`dtime`),
KEY `IX_B_F_S_G` (`bid`,`ftime`,`sid`,`grid`),
KEY `IX_B_S_G` (`bid`,`sid`,`grid`),
KEY `IX_B_D_S` (`bid`,`dtime`,`sid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
注意:mysql 只有2種索引(BTREE 和 HASH)
三:注意
1、只更新A表的部分字段:pv、uv和pay_amount
2、確定唯一一條記錄的關聯字段是:bid、sid、dtime、qrid
四:實現
1、使用inner join實現
UPDATE A as aa
INNER JOIN B as bb ON bb.bid = aa.bid
AND bb.sid=aa.sid
AND bb.grid=aa.grid
SET aa.pv=bb.pv,
aa.uv=bb.uv,
aa.pay_amount=bb.pay_amount
WHERE aa.dtime=?
AND aa.bid=? ;
2、使用exists實現
UPDATE A aa
SET aa.pv = (SELECT bb.pv
FROM B bb
WHERE bb.bid = aa.bid
AND bb.sid = aa.sid
AND bb.grid = aa.grid),
aa.uv = (SELECT bb.uv
FROM B bb
WHERE bb.bid = aa.bid
AND bb.sid = aa.sid
AND bb.grid = aa.grid),
aa.pay_amount = (SELECT bb.pay_amount
FROM B bb
WHERE bb.bid = aa.bid
AND bb.sid = aa.sid
AND bb.grid = aa.grid)
WHERE EXISTS (SELECT 1
FROM B bb
WHERE bb.bid = aa.bid
AND bb.sid = aa.sid
AND bb.grid = aa.grid)
AND aa.dtime = ?
AND aa.bid = ?;
