MySQL 由多个用户(如计数器)更新同一行 [英] MySQL updating same row by multiple users like counter

查看:32
本文介绍了MySQL 由多个用户(如计数器)更新同一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为用户帖子增加一个赞计数器.我的 MySQL 表中的一个帖子有一个字段 likes,它显示这个特定帖子有多少喜欢.现在如果多个用户同时喜欢同一个帖子会发生什么?我认为这会导致冲突或无法正确增加?如何避免这种情况,是否需要锁定行或我有哪些选项?

I'm trying to increment a like counter for a users post. A post in my MySQL table has a field likes which shows how many likes this specific post has. now what will happen if multiple user like the same post at the same time? I think this will result in a conflict or not increment correctly? How can I avoid this, do I need to lock the row or which options do I have?

我的查询可能如下所示:

my query could look something like this:

UPDATE posts
    SET likes = likes + 1,
    WHERE id = some_value

同样,当用户不喜欢某个帖子时,这应该减少 --> 喜欢 -1

also when a user unlikes a post this should decrement --> likes -1

感谢您的帮助!

推荐答案

这是一个足够简单的查询来运行:

It's a simple enough query to run:

UPDATE mytable SET mycolumn = mycolumn + 1;

这样,即使您有多个人同时点赞,查询也不会在完全相同的时间运行,因此您最终会得到正确的数字.

That way even if you have multiple people liking at the same time the queries won't run at exactly the same time and so you'll get the correct number at the end.

诸如此类的查询在几分之一秒内运行,因此您无需担心多个用户点击它们,除非您拥有数百万用户,然后您将有很多与查询相关的问题.

Queries such as these run in fractions of a second, so you don't need to worry about multiple users clicking on them unless you've got millions of users, and then you'll have lots of problems to do with queries.

这篇关于MySQL 由多个用户(如计数器)更新同一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆