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