외래 키 제한 테이블을 자르는 방법은 무엇입니까?
TRUNCATE 가 mygroup
작동 하지 않는 이유는 무엇 입니까? 나는 비록 내가 ON DELETE CASCADE SET
얻는다 :
오류 1701 (42000) : 외래 키 제약 조건 (
mytest
.instance
, CONSTRAINTinstance_ibfk_1
FOREIGN KEY (GroupID
) REFERENCESmytest
.mygroup
(ID
)) 에서 참조되는 테이블을자를 수 없습니다 .
drop database mytest;
create database mytest;
use mytest;
CREATE TABLE mygroup (
ID INT NOT NULL AUTO_INCREMENT PRIMARY KEY
) ENGINE=InnoDB;
CREATE TABLE instance (
ID INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
GroupID INT NOT NULL,
DateTime DATETIME DEFAULT NULL,
FOREIGN KEY (GroupID) REFERENCES mygroup(ID) ON DELETE CASCADE,
UNIQUE(GroupID)
) ENGINE=InnoDB;
TRUNCATE
FK 제약 조건이 적용된 테이블 은 사용할 수 없습니다 ( TRUNCATE
와 같지 않음 DELETE
).
이 문제를 해결하려면 다음 솔루션 중 하나를 사용하십시오. 둘 다 데이터 무결성을 손상시킬 위험이 있습니다.
옵션 1:
- 제약 제거
- 행하다
TRUNCATE
- 이제 아무데도 참조가 없는 행을 수동으로 삭제
- 제약 만들기
옵션 2 : 답변 에서 user447951 이 제안 함
SET FOREIGN_KEY_CHECKS = 0;
TRUNCATE table $table_name;
SET FOREIGN_KEY_CHECKS = 1;
그래 넌 할수있어:
SET FOREIGN_KEY_CHECKS = 0;
TRUNCATE table1;
TRUNCATE table2;
SET FOREIGN_KEY_CHECKS = 1;
이러한 문을 사용하면 FOREIGN KEY
제약 조건을 준수하지 않는 테이블에 행을 넣을 위험이 있습니다.
나는 단순히 다음과 같이 할 것입니다.
DELETE FROM mytest.instance;
ALTER TABLE mytest.instance AUTO_INCREMENT = 1;
넌 할 수있어
DELETE FROM `mytable` WHERE `id` > 0
당으로 MySQL의 문서 , TRUNCATE는 외래 키 관계가있는 테이블에 사용할 수 없습니다. 완전한 대안 AFAIK는 없습니다.
제약 조건을 삭제해도 ON DELETE 및 ON UPDATE가 호출되지 않습니다. ATM에서 생각할 수있는 유일한 해결책은 다음 중 하나입니다.
- 모든 행을 삭제하고, 외래 키를 삭제하고, 키를 자르고, 다시 만듭니다.
- 모든 행 삭제, auto_increment 재설정 (사용 된 경우)
MySQL의 TRUNCATE는 아직 완전한 기능이 아닌 것 같습니다 (트리거를 호출하지도 않습니다).
댓글보기
While this question was asked I didn't know about it, but now if you use phpMyAdmin you can simply open the database and select the table(s) you want to truncate.
- At the bottom there is a drop down with many options. Open it and select
Empty
option under the headingDelete data or table
. - It takes you to the next page automatically where there is an option in checkbox called
Enable foreign key checks
. Just unselect it and press theYes
button and the selected table(s) will be truncated.
Maybe it internally runs the query suggested in user447951's answer, but it is very convenient to use from phpMyAdmin interface.
Easy if you are using phpMyAdmin.
Just uncheck Enable foreign key checks
option under SQL
tab and run TRUNCATE <TABLE_NAME>
Answer is indeed the one provided by zerkms, as stated on Option 1:
Option 1: which does not risk damage to data integrity:
- Remove constraints
- Perform TRUNCATE
- Delete manually the rows that now have references to nowhere
- Create constraints
The tricky part is Removing constraints, so I want to tell you how, in case someone needs to know how to do that:
Run
SHOW CREATE TABLE <Table Name>
query to see what is your FOREIGN KEY's name (Red frame in below image):Run
ALTER TABLE <Table Name> DROP FOREIGN KEY <Foreign Key Name>
. This will remove the foreign key constraint.Drop the associated Index (through table structure page), and you are done.
to re-create foreign keys:
ALTER TABLE <Table Name>
ADD FOREIGN KEY (<Field Name>) REFERENCES <Foreign Table Name>(<Field Name>);
Just use CASCADE
TRUNCATE "products" RESTART IDENTITY CASCADE;
But be ready for cascade deletes )
Getting the old foreign key check state and sql mode are best way to truncate / Drop the table as Mysql Workbench do while synchronizing model to database.
SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;`
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';
DROP TABLE TABLE_NAME;
TRUNCATE TABLE_NAME;
SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
If the database engine for tables differ you will get this error so change them to InnoDB
ALTER TABLE my_table ENGINE = InnoDB;
참고URL : https://stackoverflow.com/questions/5452760/how-to-truncate-a-foreign-key-constrained-table
'code' 카테고리의 다른 글
Unwind segues는 무엇이며 어떻게 사용합니까? (0) | 2020.10.03 |
---|---|
C # DateTime을 "YYYYMMDDHHMMSS"형식으로 (0) | 2020.10.03 |
예 : 메시징을 사용한 활동과 서비스 간의 통신 (0) | 2020.10.03 |
Visual Studio에서 모든 대문자 메뉴 제목을 비활성화하는 방법 (0) | 2020.10.03 |
StringBuilder를 어떻게 지우거나 비울 수 있습니까? (0) | 2020.10.03 |