programing

MySQL은 외래 키 제약 조건을 만들 수 없습니다.

projobs 2021. 1. 17. 10:22
반응형

MySQL은 외래 키 제약 조건을 만들 수 없습니다.


mysql 데이터베이스의 기존 테이블에 대한 외래 키를 만드는 데 문제가 있습니다.

나는 테이블이있다 exp:

+-------------+------------------+------+-----+---------+-------+
| Field       | Type             | Null | Key | Default | Extra |
+-------------+------------------+------+-----+---------+-------+
| EID         | varchar(45)      | NO   | PRI | NULL    |       |
| Comment     | text             | YES  |     | NULL    |       |
| Initials    | varchar(255)     | NO   |     | NULL    |       |
| ExpDate     | date             | NO   |     | NULL    |       |
| InsertDate  | date             | NO   |     | NULL    |       |
| inserted_by | int(11) unsigned | YES  | MUL | NULL    |       |
+-------------+------------------+------+-----+---------+-------+

sample_df다음을 사용하여 이것을 참조 하는 새 테이블을 만들고 싶지 않습니다 .

CREATE TABLE sample_df (
df_id mediumint(5) unsigned AUTO_INCREMENT primary key,
sample_type mediumint(5) unsigned NOT NULL,
df_10 BOOLEAN NOT NULL,
df_100 BOOLEAN NOT NULL,
df_1000 BOOLEAN NOT NULL,
df_above_1000 BOOLEAN NOT NULL,
target INT(11) unsigned NOT NULL,
assay MEDIUMINT(5) unsigned zerofill NOT NULL,
insert_date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
inserted_by INT(11) unsigned NOT NULL,
initials varchar(255),
experiment VARCHAR(45),
CONSTRAINT FOREIGN KEY (inserted_by) REFERENCES user (iduser),
CONSTRAINT FOREIGN KEY (target) REFERENCES protein (PID),
CONSTRAINT FOREIGN KEY (sample_type) REFERENCES sample_type (ID),
CONSTRAINT FOREIGN KEY (assay) REFERENCES assays (AID),
CONSTRAINT FOREIGN KEY (experiment) REFERENCES exp (EID)
);

하지만 오류가 발생합니다.

ERROR 1215 (HY000): Cannot add foreign key constraint

더 많은 정보를 얻으려면 다음을 수행했습니다.

SHOW ENGINE INNODB STATUS\G

내가 얻은 :

FOREIGN KEY (experiment) REFERENCES exp (EID)
):
Cannot find an index in the referenced table where the
referenced columns appear as the first columns, or column types
in the table and the referenced table do not match for constraint.

나에게 열 유형은 둘 다 varchar (45)이기 때문에 일치하는 것 같습니다. (또한 experiment열을 null이 아닌 것으로 설정하려고 시도 했지만 이것이 수정되지 않았습니다) 그래서 문제는 Cannot find an index in the referenced table where the referenced columns appear as the first columns. 그러나 이것이 무엇을 의미하는지 또는 어떻게 확인 / 고정하는지 잘 모르겠습니다. 누구에게 제안이 있습니까? 그리고 무엇을 의미 first columns합니까?


가능한 원인의 혼합에 이것을 던져서 참조 테이블 열이 동일한 "유형"을 가지지 만 동일한 서명이 없을 때이 문제를 만났습니다.

필자의 경우 참조 된 테이블 열은 TINYINT UNSIGNED이고 참조하는 테이블 열은 TINYINT SIGNED입니다. 두 열을 모두 정렬하면 문제가 해결되었습니다.


http://dev.mysql.com/doc/refman/5.5/en/create-table-foreign-keys.html 에 따르면

MySQL은 외래 키 검사가 빠르고 테이블 스캔이 필요하지 않도록 외래 키 및 참조 된 키에 대한 인덱스가 필요합니다. 참조 테이블에는 외래 키 열이 동일한 순서의 첫 번째 열로 나열되는 인덱스가 있어야합니다.

InnoDB는 외부 키가 인덱스 열 또는 열 그룹을 참조하도록 허용합니다. 그러나 참조 된 테이블에는 참조 된 열이 동일한 순서의 첫 번째 열로 나열되는 인덱스가 있어야합니다.

따라서 참조 된 테이블에 인덱스가 존재하고 여러 컬럼으로 구성되어 있고 원하는 컬럼이 첫 번째가 아닌 경우 오류가 발생합니다.

오류의 원인은 다음 규칙을 위반했기 때문입니다.

외래 키와 참조 된 키의 해당 열은 유사한 데이터 유형을 가져야합니다. 정수 유형의 크기와 부호는 동일해야합니다. 문자열 유형의 길이가 같을 필요는 없습니다. 2 진이 아닌 (문자) 문자열 열의 경우 문자 세트와 데이터 정렬이 동일해야합니다.


이 오류는 참조 테이블과 현재 테이블에 동일한 문자 집합이없는 경우에도 발생할 수 있습니다.


As mentioned @Anton, this could be because of the different data type. In my case I had primary key BIGINT(20) and tried to set foreight key with INT(10)


In my case, it turned out the referenced column wasn't declared primary or unique.

https://stackoverflow.com/a/18435114/1763217


The exact order of the primary key also needs to match with no extra columns in between.

I had a primary key setup where the column order actually matches, but the problem was the primary key had an extra column in it that is not part of the foreign key of the referencing table

e.g.) table 2, column (a, b, c) -> table 1, column (a, b, d, c) -- THIS FAILS

I had to reorder the primary key columns so that not only they're ordered the same way, but have no extra columns in the middle:

e.g.) table 2, column (a, b, c) -> table 1, column (a, b, c, d) -- THIS SUCCEEDS


Referencing the same column more than once in the same constraint also produces this Cannot find an index in the referenced table error, but can be difficult to spot on large tables. Split up the constraints and it will work as expected.


I had this error as well. None of the answers pertained to me. In my case, my GUI automatically creates a table with a primary unique identifier as "unassigned". This fails when I try and create a foreign key and gives me the exact same error. My primary key needs to be assigned.

If you write the SQL itself like so id int unique auto_increment then you don't have this issue but for some reason my GUI does this instead id int unassigned unique auto_increment.

Hope this helps someone else down the road.


Mine was a collation issue between the referenced table and the to be created table so I had to explicitly set the collation type of the key I was referencing.

  • First I ran a query at referenced table to get its collation type
show table STATUS like '<table_name_here>';
  • Then I copied the collation type and explicitly stated employee_id's collation type at the creation query. In my case it was utf8_general_ci
CREATE TABLE dbo.sample_db
(
  id INT PRIMARY KEY AUTO_INCREMENT,
  event_id INT SIGNED NOT NULL,
  employee_id varchar(45) COLLATE utf8_general_ci NOT NULL,
  event_date_time DATETIME,
  CONSTRAINT sample_db_event_event_id_fk FOREIGN KEY (event_id) REFERENCES event (event_id),
  CONSTRAINT sample_db_employee_employee_id_fk FOREIGN KEY (employee_id) REFERENCES employee (employee_id)
);

In some cases, I had to make the referenced field unique on top of defining it as the primary key.

But I found that not defining it as unique doesn't create a problem in every case. I have not been able to figure out the scenarios though. Probably something to do with nullable definition.

ReferenceURL : https://stackoverflow.com/questions/21526055/mysql-cannot-create-foreign-key-constraint

반응형