MySQL – 如何计算一个查询中每个表的所有行

有没有办法查询数据库找出有多less行在所有的表中?

table1 1234 table2 222 table3 7888 

希望你能build议

 SELECT TABLE_NAME, TABLE_ROWS FROM `information_schema`.`tables` WHERE `table_schema` = 'YOUR_DB_NAME'; 
 SELECT table_name, table_rows FROM INFORMATION_SCHEMA.TABLES 
 select sum(cnt) from ( select count(*) as cnt from table1 union ALL select count(*) as cnt from table2 union ALL select count(*) as cnt from table3 )t1 

这将给你确切的表名称和计数在一个单一的列表

 SELECT CONCAT('SELECT ''',table_name,''', COUNT(*) FROM ', table_name, ' union all') FROM information_schema.tables WHERE table_schema = 'clw'; 

以上将给你一个近似值,但是如果你想要一个精确的计数,可以分两步完成。 首先,执行如下的查询:

 select concat("select '",table_name,"', count(*) from ",table_name,";") from `information_schema`.`tables` WHERE `table_schema` = '[your schema here]'; 

这将产生一个SQL语句列表,一个用于数据库中的每个表,然后可以运行以获得确切的计数。

将上面的信息和这个post合成为一组查询,我们得到一个自写的查询,将提供准确的行数:

 SET @tableSchema = 'my_schema'; SET SESSION group_concat_max_len = 10000000; SET @rowCounts = ( SELECT group_concat(CONCAT('SELECT ''',TABLE_NAME,''', COUNT(*) FROM ', TABLE_NAME) SEPARATOR ' union all ') FROM information_schema.tables WHERE table_schema = @tableSchema ); PREPARE statement FROM @rowCounts; EXECUTE statement; -- don't run dealloc until you've exported your results ;) DEALLOCATE PREPARE statement; 

可能想要这个,如果你只是想表和没有意见:

 SELECT TABLE_NAME, TABLE_ROWS FROM `information_schema`.`tables` WHERE `table_schema` = 'schema' AND TABLE_TYPE = 'BASE TABLE';