b.l0g.jp

渋谷ではたらくインフラエンジニアのブログ

Archive for 12月 6th, 2011

MySQLでテーブルの行数を数える

without comments


テーブル内の行数を数えるのに一番簡単なのは、

select count(*) from 'テーブル名';

と実行することだが、これだと最悪そのテーブルを総なめすることになる。
こういう時はinformation schemaから情報を引く。information_schema.tablesテーブルのtable_rowsカラムが行数。

mysql> select table_schema, table_name, table_rows from information_schema.tables
    -> where table_schema = 'hoge';
+--------------------+---------------------------------------+------------+
| table_schema       | table_name                            | table_rows |
+--------------------+---------------------------------------+------------+
| hoge               | wp_FollowMe_Links                     |          2 |
| hoge               | wp_commentmeta                        |        180 |
| hoge               | wp_comments                           |         60 |
| hoge               | wp_ktaisession                        |          0 |
| hoge               | wp_links                              |          7 |
| hoge               | wp_options                            |        236 |
| hoge               | wp_postmeta                           |        509 |
| hoge               | wp_posts                              |        323 |
| hoge               | wp_term_relationships                 |         39 |
| hoge               | wp_term_taxonomy                      |          9 |
| hoge               | wp_terms                              |          9 |
| hoge               | wp_usermeta                           |         31 |
| hoge               | wp_users                              |          2 |
+--------------------+---------------------------------------+------------+

showを使っても行数を引くことができるが、showの性質上表示させるカラムなどを細かく指定できず使いづらいこともあるので、information_schemaを引く方が好き。

show table status;

なおこれらのコマンドで引ける行数は、MyISAMなどのストレージエンジンでは正確な値だが、InnoDBの場合は概算値となる。なので、InnoDBの場合はselect count(*)するしかない。

Written by admin

12月 6th, 2011 at 3:24 pm

Posted in MySQL