是否有一种方法可以获得MySQL数据库中所有表的行计数,而无需在每个表上运行SELECT count() ?
当前回答
如果需要精确的数字,请使用下面的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.
其他回答
下面的查询生成一个(另一个)查询,该查询将从information_schema.tables中列出的每个模式中获取每个表的count(*)值。这里显示的查询的整个结果——所有行放在一起——包含一个以分号结尾的有效SQL语句——没有悬空的“联合”。在下面的查询中使用联合来避免悬空联合。
select concat('select "', table_schema, '.', table_name, '" as `schema.table`,
count(*)
from ', table_schema, '.', table_name, ' union ') as 'Query Row'
from information_schema.tables
union
select '(select null, null limit 0);';
海报想要行计数,但没有指定哪个表引擎。对于InnoDB,我只知道一种方法,那就是计数。
我是这样摘土豆的:
# Put this function in your bash and call with:
# rowpicker DBUSER DBPASS DBNAME [TABLEPATTERN]
function rowpicker() {
UN=$1
PW=$2
DB=$3
if [ ! -z "$4" ]; then
PAT="LIKE '$4'"
tot=-2
else
PAT=""
tot=-1
fi
for t in `mysql -u "$UN" -p"$PW" "$DB" -e "SHOW TABLES $PAT"`;do
if [ $tot -lt 0 ]; then
echo "Skipping $t";
let "tot += 1";
else
c=`mysql -u "$UN" -p"$PW" "$DB" -e "SELECT count(*) FROM $t"`;
c=`echo $c | cut -d " " -f 2`;
echo "$t: $c";
let "tot += c";
fi;
done;
echo "total rows: $tot"
}
我对此没有任何断言,只是说这是一种非常丑陋但有效的方法,可以获得数据库中每个表中存在多少行,而不需要使用表引擎,也不需要拥有安装存储过程的权限,也不需要安装ruby或php。是的,生锈了。是的,这很重要。Count(*)是准确的。
你可以试试这个。这对我来说很好。
SELECT IFNULL(table_schema,'Total') "Database",TableCount
FROM (SELECT COUNT(1) TableCount,table_schema
FROM information_schema.tables
WHERE table_schema NOT IN ('information_schema','mysql')
GROUP BY table_schema WITH ROLLUP) A;
简单的方法:
SELECT
TABLE_NAME, SUM(TABLE_ROWS)
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = '{Your_DB}'
GROUP BY TABLE_NAME;
结果示例:
+----------------+-----------------+
| TABLE_NAME | SUM(TABLE_ROWS) |
+----------------+-----------------+
| calls | 7533 |
| courses | 179 |
| course_modules | 298 |
| departments | 58 |
| faculties | 236 |
| modules | 169 |
| searches | 25423 |
| sections | 532 |
| universities | 57 |
| users | 10293 |
+----------------+-----------------+
我只是跑:
show table status;
这将为您提供每个表的行数以及其他一些信息。 我曾经使用上面选择的答案,但这要简单得多。
我不确定这是否适用于所有版本,但我使用5.5与InnoDB引擎。