본문 바로가기
코딩/SQL

[MySQL] Table 삭제 시 오류 : foreign key 가 있는데 truncate/delete 하는 경우

by 미생22 2023. 2. 24.
728x90

오류문구

mysql> truncate table 테이블명;
ERROR 1701 (42000): Cannot truncate a table referenced in a foreign key constraint (`데이터베이스명`.`테이블명`, CONSTRAINT `테이블명_ibfk_1`)

이유

SQL에서 truncate table할 때 ERROR 1701 (42000): Cannot truncate a table referenced in a foreign key constraint (~~) 라는 오류가 뜨는 경우, foreign key가 남아있어서 이런 오류가 뜨는 것이다.

해결방안

SET FOREIGN_KEY_CHECKS = 0; -- Disable foreign key checking.
TRUNCATE TABLE Tablename;
SET FOREIGN_KEY_CHECKS = 1; -- Enable foreign key checking.

잠시 foreign key를 해제하고 truncate 한 뒤 다시 foreign key를 재설정해주면 된다.

 

 

 

출처 : https://stackoverflow.com/questions/5452760/how-to-truncate-a-foreign-key-constrained-table

728x90

'코딩 > SQL' 카테고리의 다른 글

[MySQL] Primary Key, Foreign Key  (0) 2023.03.05
[MySQL] Python으로 SQL 사용하기  (0) 2023.02.28
[MySQL] SQL file VScode에서 실행하기  (0) 2023.02.21
AWS RDS  (0) 2023.02.21
[SQL] Concat, Alias, Distinct, Limit  (0) 2023.02.20