LoginSignup
1
0

More than 3 years have passed since last update.

【MySQL】条件に当てはまるテーブルをまとめて削除

Posted at

suffixだけが違う複数のテーブルをまとめて削除したくなった。
こういうやつ↓

test_20191013000000
test_20191013001000
test_20191013002000
...

↓でもこういうのできないしなあ…

drop table test_*;

やりかた

対象スキーマ名(=データベース名)はtest_schema
対象テーブル名はtest_の後ろにsuffixがついているとする。

1. 対象のテーブル名のカンマ区切り文字列を得る

information_schema.tablesにテーブルの情報が入っているので、条件に当てはまるものを抽出し、group_concatでテーブル名をカンマ区切りの文字列にする。
※対象テーブルが多い場合の表示を見やすく(垂直形式に表示)するために\Gをつけている。

  • likeバージョン
select group_concat(table_name)
from information_schema.tables
where table_schema = 'test_schema' and table_name like 'table\_%' \G
  • regexpバージョン
select group_concat(table_name)
from information_schema.tables
where table_schema = 'test_schema' and table_name regexp 'table_.*' \G

結果

*************************** 1. row ***************************
group_concat(table_name): table_20191013000000,table_20191013001000,table_20191013002000
1 row in set, 1 warning (0.00 sec)

※対象テーブルが多すぎる場合、途中までしか表示されないことがある。これはgroup_concatの結果文字数に制限があるため。設定を一時的に変更することで対処できる。
(参考:https://qiita.com/nwsoyogi/items/196cb92f79c6f01871e0

2. 1の結果をdrop tableの後ろに貼り付けて実行し、テーブル削除

drop table table_20191013000000,table_20191013001000,table_20191013002000;

🎉

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0