是否存在在一次操作中截断数据库中所有表的查询(命令)?我想知道我是否可以用一个查询做到这一点。
当前回答
溶液(1)
mysql> select group_concat('truncate',' ',table_name,';') from information_schema.tables where table_schema="db_name" into outfile '/tmp/a.txt';
mysql> /tmp/a.txt;
溶液2)
- Export only structure of a db
- drop the database
- import the .sql of structure
——编辑----
earlier in solution 1, i had mentioned concat() instead of group_concat() which would have not returned the desired result
其他回答
给@Mathias Bynens的回答补充一点。当我运行这个时,我得到了一个错误,因为外键检查
mysql -Nse 'SHOW TABLES' <database_name> | while read table; do mysql -e "SET FOREIGN_KEY_CHECKS=0; DROP TABLE $table" <database_name>; done
如果数据库中有视图,则返回一个错误。我必须通过drop view <view_name>手动清除视图;
PHP单命令:
php -r '$d="PUT_YOUR_DB_NAME_HERE"; $q="show tables"; $dt="drop table"; exec("mysql -Nse \"$q\" $d", $o); foreach($o as $e) `mysql -e "$dt $e" $d`;'
执行的PHP脚本:
$d="PUT_YOUR_DB_NAME_HERE";
$q="show tables";
$dt="drop table";
exec("mysql -Nse \"$q\" $d", $o);
foreach($o as $e)
`mysql -e "$dt $e" $d`;
溶液(1)
mysql> select group_concat('truncate',' ',table_name,';') from information_schema.tables where table_schema="db_name" into outfile '/tmp/a.txt';
mysql> /tmp/a.txt;
溶液2)
- Export only structure of a db
- drop the database
- import the .sql of structure
——编辑----
earlier in solution 1, i had mentioned concat() instead of group_concat() which would have not returned the desired result
mysqldump -u root -p --no-data dbname > schema.sql
mysqldump -u root -p drop dbname
mysqldump -u root -p < schema.sql
我发现最简单的方法是像下面这样做,只需用自己的表名替换表名。重要的是确保最后一行永远是 设置FOREIGN_KEY_CHECKS = 1;
SET FOREIGN_KEY_CHECKS=0;
TRUNCATE `table1`;
TRUNCATE `table2`;
TRUNCATE `table3`;
TRUNCATE `table4`;
TRUNCATE `table5`;
TRUNCATE `table6`;
TRUNCATE `table7`;
SET FOREIGN_KEY_CHECKS=1;