문제

다른 테이블의 동일한 열을 가리 키도록 테이블의 두 열에서 외래 키를 만들려고하지만 오류가 발생하는 것 같습니다 ...

여기있는 일은 다음과 같습니다.

CREATE TABLE test2 (
  ID INT NOT NULL AUTO_INCREMENT,  
  col1 INT NOT NULL,
  col2 INT NOT NULL, 
  PRIMARY KEY (ID),
  CONSTRAINT fk FOREIGN KEY (col1, col2)
                REFERENCES test1(ID, ID)
  ON UPDATE CASCADE
  ON DELETE RESTRICT
) ENGINE=InnoDB;
.

그러나 나는 얻는다

ERROR 1005 (HY000): Can't create table 'DB.test2' (errno: 150)

하나의 열만 있으면 테이블이 올바르게 생성됩니다.

누군가가 오류가있는 곳에서 나에게 지적 할 수 있습니까?

고맙습니다 n

도움이 되었습니까?

해결책

Tried it here and got the same error. This works though:

CREATE TABLE test2 (
  ID INT NOT NULL AUTO_INCREMENT,  
  col1 INT NOT NULL,
  col2 INT NOT NULL, 
  PRIMARY KEY (ID),
  CONSTRAINT fk FOREIGN KEY (col1)
                REFERENCES test1(ID)
  ON UPDATE CASCADE
  ON DELETE RESTRICT,
  CONSTRAINT fk2 FOREIGN KEY (col2)
                REFERENCES test1(ID)
  ON UPDATE CASCADE
  ON DELETE RESTRICT

) ENGINE=InnoDB

Yes, I know - your script should work (even if it doesn't seem to make much sense). Yet, I guess this new version is better.

다른 팁

The problem would appear to be that you are specifying the same parent column twice in the same foreign key (i.e, (ID, ID)). The following should work:

Create Table Test1
    (
    PK1 int not null
    , PK2 int not null
    , Primary Key ( PK1, PK2 )
    )

Create Table Test2
    (
    Id int not null Auto_Increment
    , PK1 int not null
    , PK2 int not null
    , Primary Key ( ID )
    , Constraint FK_Test2
        Foreign Key ( PK1, PK2 )
        References Test1( PK1, PK2 )
    )

If it is the case, that you want two columns in a child table referencing the same parent table column, then you must add two foreign key references as shown by rsenna as those represent two independent relations.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top