gpt4 book ai didi

php - 如何将数字添加到mysql中的当前值(同时多次)?

转载 作者:可可西里 更新时间:2023-11-01 06:27:32 24 4
gpt4 key购买 nike

我正在开发一个积分系统,该系统会根据他们的积分为我网站上的用户提供排名,每当有人检查他的个人资料页面时,我都会给用户 +1 分。假设用户有 200 点,在同一时间有 10 个用户检查了他的个人资料页面,据我了解,代码将得到 200 加 1,如果 10 个用户同时进入,结果将是 200 + 1 = 201 , 数据库将如何行动?

从逻辑上讲,它只会计算一次访问,因为用户检查配置文件的时间值为 200,因此当 MYSQL 更新发生时,它将始终为 201。我说得对吗?

最佳答案

如果您选择现有的点数,在客户端中添加一个,然后将更新后的值写回数据库,那么您将得到一个race condition。 .正如您所指出的,有些观看次数可能不会被计算在内。

相反,您应该尝试使用原子更新并避免该问题:

UPDATE user SET points = points + 1 WHERE id = 42

另一种方法是使用 SELECT ... FOR UPDATE 读取。来自documentation :

If you use FOR UPDATE with a storage engine that uses page or row locks, rows examined by the query are write-locked until the end of the current transaction. Using LOCK IN SHARE MODE sets a shared lock that permits other transactions to read the examined rows but not to update or delete them. See Section 14.2.8.3, “SELECT ... FOR UPDATE and SELECT ... LOCK IN SHARE MODE Locking Reads”

关于php - 如何将数字添加到mysql中的当前值(同时多次)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13250066/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com