首页 >> 民生呼声

的优化和索引范式和非范式覆盖

民生呼声  2021-08-24 17:42 字号: 大 中 小

Schema的优化和索引 - 范式和非范式7

每次点击都更新计数列。

mysql UPDATE hit_counter SET cnt = cnt + 1;

这样做问题在于这个单独的行是对于任意更新计数的事物是全局互斥的。它会序列化这些事物。为了获得更高的并发,可以保存更多的行并且随机更新这些行。表的修改如下

mysql CREATE TABLE hit_counter (

-    slot tinyint unsigned not null primary key,

-    cnt int unsigned not null

- ) ENGINE=InnoDB;

预先给这个表添加100行,现在这个查询就随机更新计数了。

mysql UPDATE hit_counter SET cnt = cnt + 1 WHERE slot = RAND( ) * 100;

为了获取统计信息,可以使用聚合查询

mysql SELECT SUM(cnt) FROM hit_counter;

还有一个一般需求就是需要每个周期的计数。(比如,一天一次)。如果你需要这么做,你可以修改下数据模型。

帕克5分5助攻 mysql 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;

你不想提前生成一些行,你可以使用ON DUPLICATE KEY UPDATE:

mysql INSERT INTO daily_hit_counter(day, slot, cnt)

-    VALUES(CURRENT_DATE, RAND( ) * 100, 1)

-    ON DUPLICATE KEY UPDATE cnt = cnt + 1;

如果你想减少一些行来使表变得更小,你可以写一个周期性的任务来把合并所有的结果到slot()并且上除其他的slot.

mysql UPDATE daily_hit_counter as c

-    INNER JOIN (

-       SELECT day, SUM(cnt) AS cnt, MIN(slot) AS mslot

-       FROM daily_hit_counter

-       GROUP BY day

-    ) AS x USING(day)

- SET t  = IF(ot = lot, t, 0),

-     ot = IF(ot = lot, 0, ot);

mysql DELETE FROM daily_hit_counter WHERE slot 0 AND cnt = 0;

福州前列腺炎治疗费用多少钱
南昌治疗妇科习惯性流产费用多少钱
湖州治疗前列腺炎医院
推荐资讯