How to optimize COUNT(*) performance on InnoDB by using index

前端 未结 4 1872
说谎
说谎 2020-11-28 07:32

I have a largish but narrow InnoDB table with ~9m records. Doing count(*) or count(id) on the table is extremely slow (6+ seconds):



        
4条回答
  •  有刺的猬
    2020-11-28 08:04

    Based on @Che code, you can also use triggers on INSERT and on UPDATE to perf2 in order to keep the value in stats table up to date.

    CREATE TRIGGER `count_up` AFTER INSERT ON `perf2` FOR EACH ROW UPDATE `stats`
    SET 
      `stats`.`value` = `stats`.`value` + 1 
    WHERE
      `stats`.`key` = "perf2_count";
    
    CREATE TRIGGER `count_down` AFTER DELETE ON `perf2` FOR EACH ROW UPDATE `stats`
    SET 
      `stats`.`value` = `stats`.`value` - 1 
    WHERE
      `stats`.`key` = "perf2_count";
    

    This would have the advantage of eliminating the performance issue of performing a count(*) and would only be executed when data changes in table perf2

提交回复
热议问题