자식 행을 추가하거나 업데이트 할 수 없습니다 : 외래 키 제약 조건이 실패합니다
1 번 테이블
+----------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+----------------+
| UserID | int(11) | NO | PRI | NULL | auto_increment |
| Password | varchar(20) | NO | | | |
| Username | varchar(25) | NO | | | |
| Email | varchar(60) | NO | | | |
+----------+-------------+------+-----+---------+----------------+
표 2
+------------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------------+--------------+------+-----+---------+----------------+
| UserID | int(11) | NO | MUL | | |
| PostID | int(11) | NO | PRI | NULL | auto_increment |
| Title | varchar(50) | NO | | | |
| Summary | varchar(500) | NO | | | |
+------------------+--------------+------+-----+---------+----------------+
오류:
com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException:
Cannot add or update a child row: a foreign key constraint fails
(`myapp/table2`, CONSTRAINT `table2_ibfk_1` FOREIGN KEY (`UserID`)
REFERENCES `table1` (`UserID`))
내가 뭘 잘못 했니? http://www.w3schools.com/Sql/sql_foreignkey.asp를 읽었으며 무엇이 잘못되었는지 알 수 없습니다.
현재에 저장된 값을 기반으로 필드에 table2
유효한 값이없는 행을 추가 / 업데이트하려고하기 때문에이 오류가 발생 합니다 . 더 많은 코드를 게시하면 특정 원인을 진단하는 데 도움이 될 수 있습니다.UserID
table1
에 table2
없는 UserID
값 에 삽입하려고 함을 의미합니다 table1
.
간단한 해킹은 테이블에서 작업을 수행하기 전에 외래 키 검사를 비활성화하는 것입니다. 간단히 쿼리
SET FOREIGN_KEY_CHECKS=0
이렇게하면 다른 테이블에 대한 외래 키 일치가 비활성화됩니다. 테이블 작업이 끝나면 다시 활성화하십시오.
SET FOREIGN_KEY_CHECKS=1
이것은 많은 시간 동안 나를 위해 작동합니다.
또 다른 이상한 사례를 발견했습니다. 실수로 InnoDB 테이블에서 MyISAM 테이블로 외래 키를 생성하면 데이터가 다른 경우에도 삽입시 MySQL에서이 오류가 발생합니다.
http://nick.zoic.org/art/mysql-foreign-key-error/를 참조 하십시오
table2.UserID
존재하지 않는 값 int가 있기 때문에이 오류가 발생 합니다 table1.UserID
( table2.UserID
이 외래 키를 만들기 전에 값을 수동으로 설정 한 것 같습니다).
이 장면의 예 : table1.UserID
값 1,2,3 및 table2.UserID
값 4 (수동으로 추가)를 가져옵니다. 당신이 외부 키를 만들 때, 그들은 찾을 수 UserID = 4
에서 table1
에러가 ocurse됩니다.
이 오류를 해결하려면, 단지 제거 UserID = 4
에서 table2
또는 당신은 둘 다 비우고 다음 외래 키를 생성 할 수 있습니다.
행운을 빕니다!
표 2에서 외래 키를 만들기 전에 테이블 1에 행을 삽입 한 경우 자동 증분 값이 표 1에서 2이고 표 2에서 1이기 때문에 외래 키 제약 조건 오류가 발생합니다. 표 1을 자르고 자동 증분 값을 다시 1로 설정하십시오. 그런 다음 표 2를 추가 할 수 있습니다.
방금 솔루션이 쉬운 것과 같은 문제가있었습니다.
부모 테이블에 존재 하지 않는 자식 테이블에 ID를 추가하려고 합니다.
InnoDB에는 때때로 값을 추가하지 않고 auto_increment 열을 증가시키는 버그가 있으므로 확인하십시오. INSERT ... ON DUPLICATE KEY
MyISAM 외래 키 및 트랜잭션이 지원되지 않으므로 데이터베이스 엔진을 InnoDB로 설정했는지 확인하십시오.
나는 비슷한 문제가 있었다. 내용이 있고 열이 널 입력 가능하지 않은 테이블에 외래 키를 적용하려고합니다. 두 가지 옵션이 있습니다.
- 외래 키 제약 조건을 적용하려는 열을 Null 허용으로 만듭니다. 그렇게하면 외래 키가 일부 필드가 널 입력 가능하다는 것을 알고 적용됩니다. ( 이것이 내가 한 일입니다. )
- 외래 키 제약 조건을 적용 할 열을 만들고 외래 키를 열에 삽입하는 쿼리를 작성한 다음 외래 키 제약 조건을 적용합니다. ( 이 시도하지 않았지만 작동해야 함 )
외래 키에 삽입하는 값이 부모 테이블에 있는지 확인하십시오. 그것은 나를 도왔다. 예를 들어, 당신은 삽입 할 경우 user_id = 2
에 table.2
, 그러나 table.1
이없는 user_id = 2
한 다음 제약 조건 오류가 발생합니다. 내 오류 코드 # 1452는 정확합니다. 이것이 같은 문제를 가진 다른 사람들을 돕기를 바랍니다!
약간의 수정 사항 : Table1에서 JoinColumn을 'nullable = true'로 만들고 Table2에서 'UserID'필드 'insertable = false'및 'nullable = true'를 만드십시오.
Table1 엔티티에서 :
@OneToMany(targetEntity=Table2.class, cascade = CascadeType.ALL)
@JoinColumn(name = "UserID", referencedColumnName = "UserID", nullable = true)
private List<Table2> table2List;
Table2 엔티티에서 :
@Column(insertable = false, nullable = true)
private int UserID;
나는 같은 문제가 있었고 외래 키를 추가하기 전에 첫 번째 테이블에 행이 있었기 때문입니다.
This took me a while to figure out. Simply put, the table that references the other table already has data in it and one or more of its values does not exist in the parent table.
e.g. Table2 has the following data:
UserID PostID Title Summary
5 1 Lorem Ipsum dolor sit
Table1
UserID Password Username Email
9 ******** JohnDoe john@example.com
If you try to ALTER table2 and add a foreign key then the query will fail because UserID=5 doesn't exist in Table1.
I also faced same issue and the issue was my parent table entries value not match with foreign key table value. So please try after clear all rows..
Yet another weird case that gave me this error. I had erroneously referenced my foreign keys to the id primary key. This was caused by incorrect alter table commands. I found this out by querying the INFORMATION_SCHEMA table (See this stackoverflow answer)
The table was so confused it could not be fixed by any ALTER TABLE commands. I finally dropped the table and reconstructed it. This got rid of the integrityError.
Maybe whilst you added the userID
column, there is a data for that certain table that it is established so it will have a default value of 0
, try adding the column without the NOT NULL
I also got this error: "Cannot add or update a child row: a foreign key constraint fails". I got the error when adding a new row to the parent table
The problem was that the foreign key constraint had been defined on the parent table instead of the child table.
İf you use mysql index or relation between tables, firstly you delete the colums(for example:city_id) and create new colums with same name(for example:city_id).Then try again...
Is there any existing data that the table contains? If so, try to clear out all the data in the table you want to add a foreign key. Then run the code (add a foreign key) again.
I encountered this problem so many times. This clearing out the all data in the table works when you want to add foreign key on a existing table.
Hope this works :)
child table foreign key constraint is failing
This issue may rise due to following reason:
If you are doing it in Spring mvc, you need to explicitly describe the id type, because sometimes mysql fails to recognize the type of id. so you explicitly set as in both tables in your entity class@GeneratedValue (strategy = GenerationType.IDENTITY)
'IT' 카테고리의 다른 글
log4j 로깅 계층 순서 (0) | 2020.06.03 |
---|---|
Pythons glob.glob는 어떻게 주문됩니까? (0) | 2020.06.03 |
jruby에서 float를 소수점 이하 두 자리로 반올림하는 방법 (0) | 2020.06.03 |
명령 줄 도구-오류-xcrun : 오류 : 개발자 도구가 아닌 PATH에서“xcodebuild”유틸리티를 찾을 수 없습니다. (0) | 2020.06.03 |
영문자 이외의 문자를 SQL Server의 문자열에서 제거하는 방법은 무엇입니까? (0) | 2020.06.03 |