文系プログラマによるTIPSブログ

文系プログラマ脳の私が開発現場で学んだ事やプログラミングのTIPSをまとめています。

MySQLの全テーブル・ビューのカウント結果を取得するシェルスクリプト

作っておくと後で便利だったりします〜


f:id:treeapps:20180418131549p:plain

DBを管理していると、全テーブル・ビューのカウント数を取りたい時が結構あります。

毎回カウントするのは手間暇かかるし単純作業でテンションが下がるので、シェルスクリプトを書いてみました。

#!/bin/sh

schemaName=$1
if [ -z $schemaName ]; then
    echo "Usage:<schemaName>"
    exit 1
fi
tables=($(mysql -uroot information_schema -Ne "select table_name from tables where table_schema='$schemaName';"))
views=($(mysql -uroot information_schema -Ne "select table_name from views where table_schema='$schemaName';"))

if [ -z $tables ] && [ -z $views ]; then
    echo "table and view are not found."
    exit 1
fi

sql="select "
for table in "${tables[@] views[@]}"
do
    sql="$sql(select count(*) from $table) $table,"
done
sql="$(echo $sql | sed -e 's/,$//') \G"
mysql -uroot $schemaName -e "$sql"

実行するとこんな感じに見やすく整形されます。

$ ./getAllCount.sh test
 *************************** 1. row ***************************
  enumtest: 5
    t_bulk: 0
     t_del: 0
    t_test: 317222
   t_test2: 10
   t_test3: 0
t_test_new: 3
    v_test: 317222

table_name のカラム名の部分は、-N オプションによって非表示にしているのです。

\Gオプションを付けると、半角スペースでパディングして縦に並べてくれ、更にソートまでかけてくれるので、見易い結果を得る事ができます。