我有一个mysql表:
CREATE TABLE `coupons` (
`id` INT NOT NULL AUTO_INCREMENT,
`code` VARCHAR(255),
`user_id` INT,
UNIQUE KEY `code_idx` (`code`)
) ENGINE=InnoDB;
该表由数千/数百万个代码组成,最初每个人的user_id
都为NULL。现在我有了一个web应用程序,它为同时访问该应用程序的数千名用户分配了一个唯一的代码。考虑到非常高的流量,我不确定处理这个问题的正确方法是什么。我写的查询是:
UPDATE coupons SET user_id = <some_id> where user_id is NULL limit 1;
并且该应用程序以例如1000请求/秒的并发性来运行该查询。
我观察到的是,整个表都被锁定了,这不能很好地扩展。我该怎么办?谢谢。
发布于 2019-03-12 06:24:17
可以理解,coupons
是预先填充的,并且null
user_id
被更新为非空。
explain update coupons set user_id = 1 where user_id is null limit 1;
这可能需要一个体系结构解决方案,但您可能希望在确保表具有所处理的列的索引并且便于快速更新之后查看解释。
例如,向coupons.user_id添加索引会改变MySQL的策略。
create unique index user_id_idx on coupons(user_id);
explain update coupons set user_id = 1 where user_id is null limit 1;
+----+-------------+---------+------------+-------+---------------+-------------+---------+-------+------+----------+------------------------------+
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+---------+------------+-------+---------------+-------------+---------+-------+------+----------+------------------------------+
| 1 | UPDATE | coupons | NULL | range | user_id_idx | user_id_idx | 5 | const | 6 | 100.00 | Using where; Using temporary |
+----+-------------+---------+------------+-------+---------------+-------------+---------+-------+------+----------+------------------------------+
1 row in set (0.01 sec)
因此,您应该与DBA合作,以确保数据库实体得到优化。需要考虑权衡。
此外,由于您有一个客户端应用程序,因此您有机会预取空coupons.user_id并直接在coupons.id上进行更新。很想知道你的解决方案。
https://stackoverflow.com/questions/55109670
复制相似问题