Is there a MySQL command to implement something like “drop tables except t1,b2”?

核能气质少年 提交于 2019-12-18 09:24:54

问题


I want to keep t1,t2 and drop all other tables.


回答1:


You can use information_schema to find table names, and even format the results as a bunch of DROP statements.

SELECT CONCAT('DROP TABLE ', TABLE_NAME, '; ')
  FROM information_schema.tables
  WHERE table_schema = DATABASE() AND table_name NOT IN ('foo', 'bar', 'baz');

(The DATABASE() function returns the currently use'd database.)

Using PREPARE and EXECUTE, you could even avoid copy & paste, and (in MySQL 5.0.13 and later) write a stored procedure to do this.




回答2:


You could use mysqldump to generate a list of DROP TABLE statements, filter out the ones you don't want, then pipe it back into the mysql client. Here's how we build that up

First, here's a list of DROP TABLE table statements for the database

mysqldump -uUSERNAME -pPASSWORD--add-drop-table --no-data DATABASE| \
grep ^DROP 

Now we can pipe that through grep with -v to invert the match - we want statements which don't mention the tables we're retaining (another way to do this would be --ignore-table options to mysqldump)

mysqldump -uUSERNAME -pPASSWORD--add-drop-table --no-data DATABASE| \
grep ^DROP |  
grep -v 'foo\|bar'

Finally, once you're confident, you can pipe that back into mysql

mysqldump -uUSERNAME -pPASSWORD--add-drop-table --no-data DATABASE| \
grep ^DROP | \ 
grep -v 'foo\|bar' | \
mysql -uUSERNAME -pPASSWORD DATABASE


来源:https://stackoverflow.com/questions/1454328/is-there-a-mysql-command-to-implement-something-like-drop-tables-except-t1-b2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!