简体   繁体   English

MySQL增加查看计数查询-非常慢

[英]MySQL Increase View Count Query - Very Slow

I have a site that whenever a user views a content, total view count is getting increased by 1 session-based . 我有一个网站,每当用户查看内容时,总观看次数就会增加1 个基于会话的 I am observing the slow query logs for a while and interestingly this query seems very slow. 我观察了一段时间的慢查询日志,有趣的是,此查询似乎非常慢。

Here is the query I use; 这是我使用的查询;

UPDATE video_content SET views = views+1 WHERE id = 'XXX';

Sample log; 样本日志;

UPDATE video_content SET views = views+1 WHERE id = 'XXX';
# Time: 170123 16:49:35
# User@Host: XYXY_dbE56[XYXY_dbE56] @ localhost []
# Thread_id: 6297490  Schema: XYXY  QC_hit: No
# Query_time: 3.145292  Lock_time: 0.000045  Rows_sent: 0  Rows_examined: 1
# Rows_affected: 1
SET timestamp=1485179375;

I am using MariaDB latest version running under CentOS. 我正在使用在CentOS下运行的MariaDB最新版本。 Everything is up to date and 200-400 user are online real time basis. 一切都是最新的,200-400个用户是实时在线的。

I have heavier queries than this which executes at the same time but they are fine. 我有比这同时执行的查询更重的查询,但它们很好。 Is there any way to optimize this query? 有什么方法可以优化此查询?

Thanks in advance! 提前致谢!

It can be due to row contention when u have many concurrent update on a single row. 当您在一行上有多个并发更新时,可能是由于行争用。 There're many ways to tackle that, eg, 有很多解决方法,例如

  • Use faster in-memory db such as redis 使用更快的内存数据库,例如redis

  • Use slotted schema like 使用类似

    create table counter ( id int, count int ) 创建表计数器(id int,count int)

when u increment the view u can 当您增加视图时,您可以

update counter set count+1 where id = FLOOR(RAND()*100)

And u can sum the count of all row to obtain the final counter value. 并且您可以将所有行的计数求和以获得最终的计数器值。 Assuming u have 100 counter row pre-inserted already 假设您已经预先插入了100个计数器行

Hard to say base on information that you provided. 根据您提供的信息很难说。

  1. Try to get more information whats going on with query. 尝试获取更多信息查询发生了什么。 This can be done with EXPLAIN 这可以通过EXPLAIN完成

There are many reason why query is slow. 查询缓慢的原因有很多。 This depends on the structure of table, memory for database, speed of disc (how many I/O for 1 sec), etc. 这取决于表的结构,数据库的内存,磁盘的速度(1秒内有多少个I / O)等。

If more complex queries are executed, this might be issue with table structure. 如果执行更复杂的查询,则表结构可能会出现问题。 Solution might be create separate table just for counts. 解决方案可能是只为计数创建单独的表。

You can as well use iostat to monitor CPU statistics and input/output statistics. 您也可以使用iostat监视CPU统计信息和输入/输出统计信息。

EDIT: After while I realized that I could be more specific about table structure. 编辑:经过一段时间后,我意识到我可以更详细地表结构。 There are one column indexes and multi column indexes. 一列索引和多列索引。 There might be a problem. 可能有问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM