一些网站需要缓存一个朋友数、文件下载次数之类的东西,可以创建一个独立的表来存储计数器次数,当然,为了避免对这个表的某一行的更新造成全局锁的问题,可以使用多种方法来生成多行,然后根据实时或者某个时间来合并这个多行数据,下面仅仅是一个从《mysql高性能》书里面摘取的一段
1、创建计数器表
CREATE TABLE daily_hit_counter(
day date NOT NULL,
slot TINYINT UNSIGNED not NULL,
cnt int UNSIGNED NOT NULL,
primary key(day, slot)
) ENGINE=INNODB
2、随机插入数据(可执行多次,相当于每次的点赞或者下载次数)
INSERT INTO daily_hit_counter(day, slot, cnt)
VALUES(CURRENT_DATE, RAND() * 100, 1)
ON DUPLICATE KEY UPDATE cnt = cnt +1
3、实时或者某个周期执行
UPDATE daily_hit_counter AS c
INNER JOIN (
SELECT day, SUM(cnt) cnt, min(slot) slot
FROM daily_hit_counter GROUP BY day
) as s USING(day)
SET c.cnt = IF(c.slot = s.slot,s.cnt,0),
c.slot = IF(c.slot = s.slot,0,c.slot)
4、删除其他多余行
DELETE FROM daily_hit_counter WHERE slot <> 0 AND cnt = 0