Mysql
如何從模式的所有表中獲取行數(不使用資訊模式)
查詢應該從 table name 收集數據,從 information.schema 中收集模式名稱,並且應該從實際表中獲取行數。
這實際上是一個非常好的問題,因為 MyISAM 將計數儲存在其標題中,而 InnoDB 需要完整計數(請參閱我對文章的回答Why does InnoDB store the row count?)
解決方案
使用INFORMATION_SCHEMA.TABLES創建用於計算每個表的 SQL
所有數據庫
SET group_concat_max_len = 1048576; SELECT GROUP_CONCAT(CONCAT('SELECT ',QUOTE(db),' table_schema,',QUOTE(tb), ' table_name,COUNT(1) table_rows FROM `',db,'`.`',tb,'`') SEPARATOR ' UNION ') INTO @CountSQL FROM (SELECT table_schema db,table_name tb FROM information_schema.tables WHERE table_schema NOT IN ('information_schema','performance_schema','mysql')) A; SELECT @CountSQL\G PREPARE s FROM @CountSQL; EXECUTE s; DEALLOCATE PREPARE s;
目前數據庫
SET group_concat_max_len = 1048576; SELECT GROUP_CONCAT(CONCAT('SELECT ',QUOTE(db),' table_schema,',QUOTE(tb), ' table_name,COUNT(1) table_rows FROM `',db,'`.`',tb,'`') SEPARATOR ' UNION ') INTO @CountSQL FROM (SELECT table_schema db,table_name tb FROM information_schema.tables WHERE table_schema = DATABASE()) A; SELECT @CountSQL\G PREPARE s FROM @CountSQL; EXECUTE s; DEALLOCATE PREPARE s;
特定數據庫(如
mydata
)SET group_concat_max_len = 1048576; SELECT GROUP_CONCAT(CONCAT('SELECT ',QUOTE(db),' table_schema,',QUOTE(tb), ' table_name,COUNT(1) table_rows FROM `',db,'`.`',tb,'`') SEPARATOR ' UNION ') INTO @CountSQL FROM (SELECT table_schema db,table_name tb FROM information_schema.tables WHERE table_schema = 'mydata') A; SELECT @CountSQL\G PREPARE s FROM @CountSQL; EXECUTE s; DEALLOCATE PREPARE s;
要查看生成的 SQL,請執行此
SELECT @CountSQL\G
試一試 !!!
請參閱https://dev.mysql.com/doc/refman/8.0/en/tables-table.html上的文件