5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[MySQL] "Cannot truncate a table referenced in a foreign key constraint" 外部キー制約でtruncate tableできなかった時の対応

Posted at

あんまりtruncate tableする機会がいままでなかったのですが、mysqlでtruncateしようとしたら、外部キーの制約があるからできませんってエラーが出てきたとき、どうしてもtruncateしたい場合は次の様に外部キーチェックを一度キルトいいようです。

mysql> truncate table messages;
ERROR 1701 (42000): Cannot truncate a table referenced in a foreign key constraint (`database_name`.`table_name`, CONSTRAINT `foreign_key_name` FOREIGN KEY (`foreign_key_culumn_name`) REFERENCES `database_name`.`target_table_name` (`id`))
mysql> set foreign_key_checks = 0;
mysql> truncate table table_name;
mysql> set foreign_key_checks = 1;
5
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?