显示表名+ mysql innodb数据库中每个表的记录数


10

如何列出当前数据库中的所有表以及表的行数。

换句话说,您能想到在mysql中提出类似查询的查询吗?

+------------------------++------------------------+
| Tables_in_database     |  Number of rows         |
+------------------------++------------------------+
| database 1             |   1000                  |
| database 2             |   1500                  |
+------------------------++------------------------+

欢迎使用不同的方法。


您正在使用MyISAM还是InnoDB?你看过这个问题了吗?
亚伦·伯特兰

@AaronBertrand谢谢,这个问题很有趣。我使用innodb
sjdh 2014年

Answers:


8

我有一个使用蛮力动态SQL的非常激进的方法

SET group_concat_max_len = 1024 * 1024 * 100;
SELECT CONCAT('SELECT * FROM (',GROUP_CONCAT(CONCAT('SELECT ',QUOTE(tb),' Tables_in_database,
COUNT(1) "Number of Rows" FROM ',db,'.',tb) SEPARATOR ' UNION '),') A;')
INTO @sql FROM (SELECT table_schema db,table_name tb
FROM information_schema.tables WHERE table_schema = DATABASE()) A;
PREPARE s FROM @sql; EXECUTE s; DEALLOCATE PREPARE s;

示例:在我的测试数据库中,我得到了

mysql> use test
Database changed
mysql> SET group_concat_max_len = 1024 * 1024 * 100;
Query OK, 0 rows affected (0.00 sec)

mysql> SELECT CONCAT('SELECT * FROM (',GROUP_CONCAT(CONCAT('SELECT ',QUOTE(tb),' Tables_in_database,
    '> COUNT(1) "Number of Rows" FROM ',db,'.',tb) SEPARATOR ' UNION '),') A;')
    -> INTO @sql FROM (SELECT table_schema db,table_name tb
    -> FROM information_schema.tables WHERE table_schema = DATABASE()) A;
Query OK, 1 row affected (0.00 sec)

mysql> PREPARE s FROM @sql; EXECUTE s; DEALLOCATE PREPARE s;
Query OK, 0 rows affected (0.00 sec)
Statement prepared

+--------------------+----------------+
| Tables_in_database | Number of Rows |
+--------------------+----------------+
| biblio             |              3 |
| biblio_old         |              7 |
| dep                |              5 |
| e                  |             14 |
| emp                |              4 |
| fruit              |             12 |
| fruit_outoforder   |             12 |
| nums_composite     |              0 |
| nuoji              |              4 |
| prod               |              3 |
| prodcat            |              6 |
| test2              |              9 |
| worktable          |              5 |
| yoshi_scores       |             24 |
+--------------------+----------------+
14 rows in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

mysql>

试试看 !!!

CAVEAT:如果所有表都是MyISAM,这将很快发生。如果所有表都是InnoDB,将对每个表进行计数。对于非常大的InnoDB表而言,这可能是残酷且无情的。


这是动态SQL的一个很好的例子。谢谢!
sjdh 2014年

我试图取代FROM information_schema.tablesFROM show tables。您能解释为什么这行不通吗?
sjdh 2014年

哇,这非常有用!
汤米

我很乐意看到迭代所有数据库的版本。我尝试运行,SELECT DISTINCT table_schema FROM information_schema.tables但不知道如何包装查询以在这些结果上运行。如果我能找到答案,我会张贴在dba.stackexchange.com/q/201880/18098
Ryan

实际上,我发现您已经在dba.stackexchange.com/a/102284/18098上回答了,但至少有一个错字。即使修复了“ DEALLCOATE”,也无法运行您的“所有数据库”版本。我不熟悉SELECT @CountSQL\G
Ryan

6

在没有动态查询的情况下尝试以下查询

SELECT Table_name AS TablesInDatabase ,table_rows AS NumberOfRows 
FROM information_schema.tables 
WHERE Table_schema=DATABASE(); 

1
此方法仅对全MyISAM数据库可靠。InnoDB不会在其体系结构的任何部分或INFORMATION_SCHEMA中存储行数。(请参阅我的文章dba.stackexchange.com/questions/17926/…)。针对INFORMATION_SCHEMA的动态方法是InnoDB表的唯一方法。
RolandoMySQLDBA 2014年

感谢您分享此方法。我可以确认该方法为我的某些表提供的计数稍有不同。我所有的表都存储在InnoDB存储引擎中。
sjdh 2014年

最好的答案,就像魅力。
Pablo Pazos

1

也许此查询可能有所帮助。它显示数据大小和记录数。

SET @table=(SELECT DATABASE());
select @table;
SELECT 
     table_schema as `Database`, 
     table_name AS `Table`, 
     round(((data_length + index_length) / 1024 / 1024), 2) `Size in MB`,
     table_rows as 'Rows'
FROM information_schema.TABLES 
WHERE table_schema = @table
ORDER BY (data_length + index_length) DESC;

1

使用shell脚本获取MySQL中所有表的确切行数。

将parameter.config文件中的参数设置为

# Server Details
host_server=10.109.25.37

# Mysql credentials
mysql_user=root
mysql_pass=root
mysql_port=3306

要计数的脚本是:

#!/bin/bash
# This Script is used to take rows count of mysql all user database

# Read Parameter
source parameter.config

# Find path
MY_PATH="`dirname \"$0\"`"
#echo "$MY_PATH"

start=`date +%s`
echo -e "\n\n"
echo MySQL script start runing at Date and Time is: `date +"%D %T"`
echo -e "@@@ Start of rows Count of MySQL on Old Ficus Release $host_server @@@"

echo -e "\n***** MySQL Rows Count Start *****"

#Make directory to save rows count
NOW="$(date +%Y%m%dT%H%M%S)"
dir_name="mysqlRows_$host_server"
if [ ! -d "$MY_PATH/$dir_name" ]; then
    mkdir "$MY_PATH/$dir_name"
fi
echo -e "\n..... Directory $dir_name is Created for mysql....."

echo -e "\n..... Check MySQL Connection ....."
# Verifying mysql connections on new release machine
MYSQL_CONN="-u$mysql_user -p$mysql_pass -h$host_server"
mysql ${MYSQL_CONN} -e "exit"
if [ $? -eq 0 ];
then
    echo -e "\n..... MySQL Database Connection Successful on server $host_server ....."
else
    echo -e "\n..... MySQL Database Connection Fail. Please verify $host_server credential ....."
    exit
fi

echo -e "\nReading MySQL database names..."
mysql ${MYSQL_CONN} -ANe "SELECT schema_name FROM information_schema.schemata WHERE schema_name NOT IN ('mysql','information_schema','performance_schema')" > $MY_PATH/$dir_name/dbs_$NOW.txt
DBS="$(cat $MY_PATH/$dir_name/dbs_$NOW.txt)"
# echo -e "\nList of databases:\t" ${DBS}

echo -e "\n..... Running for row count of tables of all user databases ....."

# All User databases
for db in ${DBS[@]}
do
    # echo $db , ${db[@]} 
    # Find list of database
    echo -e "\n\t... Running for ${db[@]} database tables list ..."
    mysql ${MYSQL_CONN} -ANe "SELECT  TABLE_NAME FROM information_schema.TABLES WHERE  TABLE_SCHEMA IN ('${db[@]}')" > $MY_PATH/$dir_name/${db[@]}_tables_$NOW.txt
    TBL="$(cat $MY_PATH/$dir_name/${db[@]}_tables_$NOW.txt)"
    # echo "Table in $db are:" ${TBL[@]}, $MY_PATH/$dir_name/${db[@]}_tables.txt

    echo -e "\n\t... Running for ${db[@]} database tables rows count ..."
    for tbs in ${TBL[@]}
    do
        # echo $tbs , ${tbs[@]}
        count=$(mysql -u$mysql_user -p$mysql_pass -h$host_server ${db[@]} -N -e "select count(*) from ${tbs[@]}")
        # count="$(cat /tmp/$db_rows_$NOW.txt)"
        # echo "Row in $tb Table of $db database are:" ${count[@]}
        echo -e "${db[@]},${tbs[@]},$count" >> $MY_PATH/$dir_name/${db[@]}_rows_$NOW.csv
        echo -e "${db[@]},${tbs[@]},$count" >> $MY_PATH/$dir_name/alldbs_rows_$NOW.csv
    done
done
echo -e "\n..... End of rows count of tables of all databases ....."

echo -e "\n===== MySQL Rows Count End ====="

# Display script execution time.
echo -e "@@@ Completion of Rows Count of MySQL on old Release $host_server @@@"
echo Script ended at Date and Time is: `date +"%D %T"`
end=`date +%s`
runtime=$((end-start))
echo -e "Time(in second) taken for running MySQL row count script:" $runtime "Sec."

将此保存在文件“ mysqlrowscount.sh”中,使用以下命令运行此脚本:

bash mysqlrowscount.sh
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.