您的位置:首页 > 数据库 > MySQL

清空mysql指定库里所有表数据

2012-11-06 14:46 429 查看
由于项目需要将之前那些测试数据全部清空,几经询问,终于问到一个答案出来,原来可以对mysql中的information_schema这个库里进行操作的。具体可执行:

select * from REFERENTIAL_CONSTRAINTS

来查看这个系统表里的字段及数据。

代码如下:

select CONCAT( 'alter table ', table_name,' drop foreign key ', constraint_name,';') as mystr from REFERENTIAL_CONSTRAINTS where unique_constraint_schema= 'sams4' and table_name in (

select table_name from REFERENTIAL_CONSTRAINTS where unique_constraint_schema= 'sams4'

);

select CONCAT( 'truncate table ', table_name,';') as mystr from REFERENTIAL_CONSTRAINTS where unique_constraint_schema= 'sams4' and table_name in (

select table_name from REFERENTIAL_CONSTRAINTS where unique_constraint_schema= 'sams4'

);

select CONCAT( 'alter table ', table_name,' drop foreign key ', constraint_name,';') as mystr from REFERENTIAL_CONSTRAINTS where unique_constraint_schema= 'sams4' and table_name in (

select table_name from REFERENTIAL_CONSTRAINTS where unique_constraint_schema= 'sams4' nd table_name like 't_%'

);

select CONCAT( 'truncate table ', table_name,';') as mystr from REFERENTIAL_CONSTRAINTS where unique_constraint_schema= 'sams4' and table_name in (

select table_name from REFERENTIAL_CONSTRAINTS where unique_constraint_schema= 'sams4' and table_name like 't_%'

);

其中sams4是我指定的库!以上代码只是一个查出全部表,一个查出所有以t_开头的表名,都是先将表与表之间的外键关联删除后再进行清空表,清空表时用的是truncate table,并不是用delete from table的语句是因为用truncate这个命令里,可以将ID值重置为1.

但这里还有一个问题,就是外键关联的问题,如果要清空表数据的话,一个一个的按顺序来清空,工作量也太大了,如果有办法可以先暂时将这个外键屏蔽的话就好了,所以上网google一下,得出如下:

SET FOREIGN_KEY_CHECKS = 0; #取消外键关联

【执行操作,操作结束后】

SET FOREIGN_KEY_CHECKS = 1; #开启外键关联

至此应该可以有效率地将库里的指定表数据清空!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: