Insert into select语句引发的生产事故!
往期热门文章:
前言
insert into select
实现,这样就可以避免使用网络I/O,直接使用SQL依靠数据库I/O完成,这样简直不要太棒了。然后他就被开除了。事故发生的经过。
在迁移的过程中,应急群是先反应有小部分用户出现支付失败,随后反应大批用户出现支付失败的情况,以及初始化订单失败的情况,同时腾讯也开始报警。
然后xxx就慌了,立即停止了迁移。
事故还原
建立表结构
CREATE TABLE `order_today` (
`id` varchar(32) NOT NULL COMMENT '主键',
`merchant_id` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '商户编号',
`amount` decimal(15,2) NOT NULL COMMENT '订单金额',
`pay_success_time` datetime NOT NULL COMMENT '支付成功时间',
`order_status` varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '支付状态 S:支付成功、F:订单支付失败',
`remark` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '备注',
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '修改时间 -- 修改时自动更新',
PRIMARY KEY (`id`) USING BTREE,
KEY `idx_merchant_id` (`merchant_id`) USING BTREE COMMENT '商户编号'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
订单记录表
CREATE TABLE order_record like order_today;
今日订单表数据
模拟迁移
把8号之前的数据都迁移到
order_record
表中去。INSERT INTO order_record SELECT
*
FROM
order_today
WHERE
pay_success_time < '2020-03-08 00:00:00';
在navicat中运行迁移的sql,同时开另个一个窗口插入数据,模拟下单。
出现的原因
insert into order_record select * from order_today
加锁规则是:order_record
表锁,order_today
逐步锁(扫描一个锁一个)。分析执行过程。
order_today
是全表扫描,也就意味着在执行insert into select from
语句时,mysql会从上到下扫描order_today
内的记录并且加锁,这样一来不就和直接锁表是一样了。解决方案
order_today
全表扫描,什么能避免全表扫描呢,很简单嘛,给pay_success_time
字段添加一个idx_pay_suc_time
索引就可以了,由于走索引查询,就不会出现扫描全表的情况而锁表了,只会锁定符合条件的记录。最终的sql
INSERT INTO order_record SELECT
*
FROM
order_today FORCE INDEX (idx_pay_suc_time)
WHERE
pay_success_time <= '2020-03-08 00:00:00';
执行过程
总结
insert into tablA select * from tableB
语句时,一定要确保tableB
后面的where
,order
或者其他条件,都需要有对应的索引,来避免出现tableB
全部记录被锁定的情况。参考文章
- insert into … select 由于SELECT表引起的死锁情况分析
最新评论
推荐文章
作者最新文章
你可能感兴趣的文章
Copyright Disclaimer: The copyright of contents (including texts, images, videos and audios) posted above belong to the User who shared or the third-party website which the User shared from. If you found your copyright have been infringed, please send a DMCA takedown notice to [email protected]. For more detail of the source, please click on the button "Read Original Post" below. For other communications, please send to [email protected].
版权声明:以上内容为用户推荐收藏至CareerEngine平台,其内容(含文字、图片、视频、音频等)及知识版权均属用户或用户转发自的第三方网站,如涉嫌侵权,请通知[email protected]进行信息删除。如需查看信息来源,请点击“查看原文”。如需洽谈其它事宜,请联系[email protected]。
版权声明:以上内容为用户推荐收藏至CareerEngine平台,其内容(含文字、图片、视频、音频等)及知识版权均属用户或用户转发自的第三方网站,如涉嫌侵权,请通知[email protected]进行信息删除。如需查看信息来源,请点击“查看原文”。如需洽谈其它事宜,请联系[email protected]。