简体   繁体   中英

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 . 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. Everything is up to date and 200-400 user are online real time basis.

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

  • Use slotted schema like

    create table counter ( 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

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

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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