是否有一种方法可以获得MySQL数据库中所有表的行计数,而无需在每个表上运行SELECT count() ?
当前回答
我不知道为什么这么难,但这就是生活。 下面是执行实际计数的bash脚本。只需将其保存为(例如count_rows.sh),使其可执行(例如chmod 755 count_rows.sh),并运行它(例如。/count_rows.sh)
#!/bin/bash
readarray -t TABLES < <(mysql --skip-column-names -u myuser -pmypassword mydbname -e "show tables")
# now we have an array like:
# TABLES='([0]="customer" [1]="order" [2]="product")'
# You can print out the array with:
#declare -p TABLES
for i in "${TABLES[@]}"
do
#echo $i
COUNT=$(mysql --skip-column-names -u username -pmypassword mydbname -e "select count(*) from $i")
echo $i : $COUNT
done
其他回答
如果你使用数据库information_schema,你可以使用下面的mysql代码(where部分使查询不显示行为空值的表):
SELECT TABLE_NAME, TABLE_ROWS
FROM `TABLES`
WHERE `TABLE_ROWS` >=0
如果需要精确的数字,请使用下面的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);';
下面的代码为所有故事生成选择查询。只需删除最后的“UNION ALL”选择所有结果,并粘贴一个新的查询窗口运行。
SELECT
concat('select ''', table_name ,''' as TableName, COUNT(*) as RowCount from ' , table_name , ' UNION ALL ') as TR FROM
information_schema.tables where
table_schema = 'Database Name'
SELECT TABLE_NAME,SUM(TABLE_ROWS)
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'your_db'
GROUP BY TABLE_NAME;
这就是你所需要的。
推荐文章
- 如何关闭mysql密码验证?
- 如何在Ruby On Rails中使用NuoDB手动执行SQL命令
- 查询JSON类型内的数组元素
- 确定记录是否存在的最快方法
- MySQL区分大小写查询
- 获得PostgreSQL数据库中当前连接数的正确查询
- 在SQL选择语句Order By 1的目的是什么?
- MySQL数据库表中的最大记录数
- 原则-如何打印出真正的sql,而不仅仅是准备好的语句?
- PHP/MySQL插入一行然后获取id
- 我如何循环通过一组记录在SQL Server?
- 如何从命令行通过mysql运行一个查询?
- 外键约束可能导致循环或多条级联路径?
- 使用LIMIT/OFFSET运行查询,还可以获得总行数
- 当恢复sql时,psql无效命令\N