是否有一种方法可以获得MySQL数据库中所有表的行计数,而无需在每个表上运行SELECT count() ?


当前回答

如果你知道表的数量和它们的名称,并且假设它们每个都有主键,你可以使用交叉连接结合COUNT(distinct [column])来获得来自每个表的行:

SELECT 
   COUNT(distinct t1.id) + 
   COUNT(distinct t2.id) + 
   COUNT(distinct t3.id) AS totalRows
FROM firstTable t1, secondTable t2, thirdTable t3;

下面是一个SQL Fiddle的例子。

其他回答

如果你知道表的数量和它们的名称,并且假设它们每个都有主键,你可以使用交叉连接结合COUNT(distinct [column])来获得来自每个表的行:

SELECT 
   COUNT(distinct t1.id) + 
   COUNT(distinct t2.id) + 
   COUNT(distinct t3.id) AS totalRows
FROM firstTable t1, secondTable t2, thirdTable t3;

下面是一个SQL Fiddle的例子。

大多数其他答案建议使用INFORMATION_SCHEMA。但是在MySQL 8中它已经不存在了。行数已移动到INFORMATION_SCHEMA.INNODB_TABLESTATS。

你可以用以下方法查询:

SELECT *
FROM information_schema.INNODB_TABLESTATS
WHERE NAME LIKE "YOUR_DB_NAME/%"
ORDER BY NUM_ROWS DESC

请注意,这仍然是一个近似值,像以前一样,不是一个确切的数字。

如果你使用数据库information_schema,你可以使用下面的mysql代码(where部分使查询不显示行为空值的表):

SELECT TABLE_NAME, TABLE_ROWS
FROM `TABLES`
WHERE `TABLE_ROWS` >=0

我只是跑:

show table status;

这将为您提供每个表的行数以及其他一些信息。 我曾经使用上面选择的答案,但这要简单得多。

我不确定这是否适用于所有版本,但我使用5.5与InnoDB引擎。

如果需要精确的数字,请使用下面的ruby脚本。你需要Ruby和RubyGems。

安装以下Gems:

$> gem install dbi
$> gem install dbd-mysql

文件:count_table_records.rb

require 'rubygems'
require 'dbi'

db_handler = DBI.connect('DBI:Mysql:database_name:localhost', 'username', 'password')

# Collect all Tables
sql_1 = db_handler.prepare('SHOW tables;')
sql_1.execute
tables = sql_1.map { |row| row[0]}
sql_1.finish

tables.each do |table_name|
  sql_2 = db_handler.prepare("SELECT count(*) FROM #{table_name};")
  sql_2.execute
  sql_2.each do |row|
    puts "Table #{table_name} has #{row[0]} rows."
  end
  sql_2.finish
end

db_handler.disconnect

回到命令行:

$> ruby count_table_records.rb

输出:

Table users has 7328974 rows.