I have this MySQL table:
video (id int, name varchar(30), view_count int)
I tried to run the following query on my computer:
update `video` set view_count = view_count + 1 where id = 1;
It works fine.
However, after I moved the database to another server, the above update query sometimes work, sometimes not work. It doesn’t have any error message, but the value doesn’t change.
I tried to run:
update `video` set name = 'testing', view_count = view_count + 1 where id = 1;
The name can be updated successfully, but the vide_count doesn’t change..
Anyone know what problem it is?
Here is the output from MySQL prompt:
update `video` set view_count = view_count + 1 where id = 1;
Query OK, 1 row affected (0.13 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> show create table video \G;
*************************** 1. row ***************************
Table: video
Create Table: CREATE TABLE `video` (
`id` int(10) unsigned NOT NULL auto_increment,
`name` varchar(30) default NULL,
`view_count` int(10) default NULL,
PRIMARY KEY (`id`),
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8
1 row in set (0.00 sec)
mysql> select * from video;
| id | name | view_count |
| 1 | ABC | 8510 |
MyISAM performs a full table lock on any DML (INSERT, UPDATE, DELETE)
If the video table is MyISAM, that should take care of this problem because only one person is allowed to have exclusive write privilege on the table executing a single DML statement, even if 1000 people are trying to execute
InnoDB performs MVCC around any data you are updating. Since the default is REPEATABLE-READ, 1000 people may see the same value for view_count just before attempting to increment it. Thus, if DB Connection #1 sees view_count as 12, increments it, it should be 13. However, if DB Connection #2 sees view_count as 12, it wiil increment it, and be 13 AGAIN !!!
Keep in mind that I am only speculating based on multiple DB Connections attempting the exact same UPDATE query.