mysql table_rows统计


查元数据表,有时候不准,因为统计信息的缘故,表的量到了千万级别了,查 information_schema.tables非常不准,于是自己写了一个函数,一次统计统计自己需要的表的行数。

因为要估算添加索引的耗时,我的表都是类似这种,t_user_message_0,t_user_message_1,t_user_message_2,t_user_message_xxx,因为有规律,且数据多,有200张左右,写一个批量运行select count(*) from xx;

这种且插入到一张表(顺便放一列显示最近半年数据看占比多少),得出每张表的数据量。

(1)创建存储表行数的表:

CREATE TABLE `tb_rows` (
  `id` int NOT NULL AUTO_INCREMENT,
  `col1` int DEFAULT NULL,
  `col2` int DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4

(2)创建函数收集表行数:

create
    definer = devops@`%` procedure fn_table_rows_im2()
begin
    declare userMessageIndex int default 0;
    declare messageIndex int default 0;
    declare commond_sql varchar(5000);
    while(userMessageIndex < 300) do
        set messageIndex = 0;
        begin
            while (messageIndex < 1) doset commond_sql = concat(' insert into tb_rows(col1,col2)select count(*),count(case when _dt>=date_add(curdate(),interval -6 month) then 1 end)col2',' from ','t_user_message_',userMessageIndex);
                set @sql = commond_sql;
                PREPARE stmt FROM @sql;         -- 预处理动态sql语句
                EXECUTE stmt ;                        -- 执行sql语句
                deallocate prepare stmt;      -- 释放prepare
                set messageIndex = messageIndex + 1;  
            end while;
        end;
        set userMessageIndex = userMessageIndex + 1;
    end while;
end;

最后运行结束直接查tb_rows就行了。

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM