开发者

Drop tables in MySQL

I have a database with tables some examples named "_data", "_keep", "foo", "bar"

Without dropping all tables in Db, How do I drop all tables that dont start with "_". In above example foo and bar.

Using Sql

Having problem with keywords used as table names, is there away to Not to drop "_" but drop any tables older than 10 minutes. (I wanted to drop before table creation. now looking to do drop after upd开发者_开发技巧ate.)


set @str = (select concat('drop table ', group_concat(table_name separator ','),';')
from information_schema.tables
where table_schema = 'your_database_name' and table_name not regexp '^_');
prepare stmt from @str;
execute stmt;
deallocate prepare stmt;

edit. I answer you here because it's more readable. If you want to retrieve only tables created more than 10 minutes ago you have to do

select table_name from information_schema.tables
where table_schema = 'your_db'
and now() - interval 10 minute > create_time 

Apply where clause to my previous code. I hope this is what you're looking for.


delimiter $$
create procedure drop_tables_like(pattern varchar(255), db varchar(255))
begin
select @str_sql:=concat('drop table ', group_concat(table_name))
from information_schema.tables
where table_schema=db and table_name like pattern;

prepare stmt from @str_sql;
execute stmt;
drop prepare stmt;
end$$

call drop_tables_like('_%', 'db_1')$$

drop procedure if exists drop_tables_like$$
delimiter ;


The following line:

mysqldump -u [username] -p [password] --add-drop-table --no-data [databasename]|grep ^DROP

produces a list of all tables, like this:

DROP TABLE IF EXISTS `agenda`;
DROP TABLE IF EXISTS `bla`;
DROP TABLE IF EXISTS `test`;
DROP TABLE IF EXISTS `users`;

Filter that list with "grep" and pipe it back into mysql.

mysqldump -u [username] -p [password] --add-drop-table --no-data [databasename] | \
    grep -E "^DROP TABLE IF EXISTS .[^_]" | mysql -u [username] -p [password] [databasename]


Check out mk-find. It will allow you to run commands against your server, and, based on the results of those commands, run other commands.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜