I have a clicks count for a thing on my website. For example, each user profile can appear 500 times on a page. Each time it appears I will reduce 1.
CREATE TABLE IF NOT EXISTS `show_profile` (
`id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`user` INT(11) UNSIGNED NOT NULL,
`count`INT(11) UNSIGNED NOT NULL,
`data` datetime NOT NULL,
PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
count has 500. each time it appears (rand) I will remove 1. 499, 498. But this count must be precise. if 2 users open a page at the same time and mysql gets 499 for both, it will reduce 1 only.
Any ideas how to do it precisely?
Each sql query is executed atomic. This means, if you decrement the counter inside the sql statement, you always get the correct result - even if two queries are executed at exactly the same time.
UPDATE show_profile SET count = count - 1 WHERE id = ? AND count > 0