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

由于项目需要将之前那些测试数据全部清空,几经询问,终于问到一个答案出来,原来可以对mysql中的information_schema这个库里进行操作的。具体可执行: 
  1. select * from REFERENTIAL_CONSTRAINTS  

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

代码如下: 
  1. 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 (  
  2. select table_name from REFERENTIAL_CONSTRAINTS where unique_constraint_schema= 'sams4'  
  3. );  
  4.   
  5.   
  6. select CONCAT( 'truncate table ', table_name,';')  as mystr from REFERENTIAL_CONSTRAINTS where unique_constraint_schema= 'sams4' and table_name in (  
  7. select table_name from REFERENTIAL_CONSTRAINTS where unique_constraint_schema= 'sams4'  
  8. );  
  9.   
  10.   
  11. 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 (  
  12. select table_name from REFERENTIAL_CONSTRAINTS where unique_constraint_schema= 'sams4' nd table_name like 't_%'  
  13. );  
  14.   
  15. select CONCAT( 'truncate table ', table_name,';')  as mystr from REFERENTIAL_CONSTRAINTS where unique_constraint_schema= 'sams4' and table_name in (  
  16. select table_name from REFERENTIAL_CONSTRAINTS where unique_constraint_schema= 'sams4' and table_name like 't_%'  
  17. );  


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

但这里还有一个问题,就是外键关联的问题,如果要清空表数据的话,一个一个的按顺序来清空,工作量也太大了,如果有办法可以先暂时将这个外键屏蔽的话就好了,所以上网google一下,得出如下: 
  1. SET FOREIGN_KEY_CHECKS = 0;  #取消外键关联  
  2. 【执行操作,操作结束后】  
  3. SET FOREIGN_KEY_CHECKS = 1;   #开启外键关联  

至此应该可以有效率地将库里的指定表数据清空! 
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值