是否存在在一次操作中截断数据库中所有表的查询(命令)?我想知道我是否可以用一个查询做到这一点。
当前回答
SET FOREIGN_KEY_CHECKS = 0;
SELECT @str := CONCAT('TRUNCATE TABLE ', table_schema, '.', table_name, ';')
FROM information_schema.tables
WHERE table_type = 'BASE TABLE'
AND table_schema IN ('db1_name','db2_name');
PREPARE stmt FROM @str;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET FOREIGN_KEY_CHECKS = 1;
其他回答
溶液(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
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`;
以这种方式使用phpMyAdmin:
Database View => Check All (tables) =>空
如果你想忽略外键检查,你可以取消选中下面的复选框:
[]启用外键检查
您至少需要运行4.5.0或更高版本才能获得此复选框。
它不是MySQL CLI-fu,但是,嘿,它工作!
SET FOREIGN_KEY_CHECKS = 0;
SELECT @str := CONCAT('TRUNCATE TABLE ', table_schema, '.', table_name, ';')
FROM information_schema.tables
WHERE table_type = 'BASE TABLE'
AND table_schema IN ('db1_name','db2_name');
PREPARE stmt FROM @str;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET FOREIGN_KEY_CHECKS = 1;
如果使用SQL server 2005,有一个隐藏的存储过程,允许您对数据库中的所有表执行一个或一组命令。下面是如何用这个存储过程调用TRUNCATE TABLE:
EXEC [sp_MSforeachtable] @command1="TRUNCATE TABLE ?"
这里有一篇很好的文章进一步阐述。
然而,对于MySql,你可以使用mysqldump并指定——add-drop-tables和——no-data选项来删除和创建所有忽略数据的表。是这样的:
mysqldump -u[USERNAME] -p[PASSWORD] --add-drop-table --no-data [DATABASE]
Mysqldump使用指南