Domanda

I am creating a database table. Specifically this code will not add the two foreign keys for some reason, it says cannot add foreign key constraints, I'll show you the tables that I'm referring to.

mysql> ALTER TABLE PROGRAM
-> ADD SeriesName varchar(100) NOT NULL, ADD StartYear char(4) NOT NULL,
-> ADD CONSTRAINT program_seriesname_fk
-> FOREIGN KEY(SeriesName) REFERENCES SERIES(SeriesName),
-> ADD CONSTRAINT program_startyear_fk
-> FOREIGN KEY(StartYear) REFERENCES SERIES(StartYear);
ERROR 1215 (HY000): Cannot add foreign key constraint

SERIES table has PROGRAM table which means it is a 1:N (one-to-many relationship). So therefore, the two primary keys in SERIES become the two foreign keys in PROGRAM.

mysql> describe series;
+------------+--------------+------+-----+---------+-------+
| Field      | Type         | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+-------+
| SeriesName | varchar(100) | NO   | PRI |         |       |
| StartYear  | char(4)      | NO   | PRI |         |       |
| EndYear    | char(4)      | YES  |     | NULL    |       |
+------------+--------------+------+-----+---------+-------+
3 rows in set (0.07 sec)

mysql> describe program;
+-------------+--------------+------+-----+---------+-------+
| Field       | Type         | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------+-------+
| ProgramName | varchar(50)  | NO   | PRI |         |       |
| Description | varchar(255) | YES  |     | NULL    |       |
| Recorded    | date         | NO   |     | NULL    |       |
+-------------+--------------+------+-----+---------+-------+
3 rows in set (0.01 sec)
È stato utile?

Soluzione

You have composite PK on series table, so you can't use this fields separately in FK constraint

 ADD CONSTRAINT program_seriesname_fk
 FOREIGN KEY(SeriesName, StartYear) REFERENCES SERIES(SeriesName, StartYear)

Altri suggerimenti

To create a foreign key to a single column in InnoDB, the column you reference needs to be the first column in at least one index.

ALTER TABLE program
  ADD CONSTRAINT program_startyear_fk
  FOREIGN KEY(StartYear) REFERENCES SERIES(StartYear);

will not work, since SERIES(StartYear) is the second column in the primary key index on SERIES. If you add an index first though;

CREATE INDEX ix_program ON series(StartYear);
ALTER TABLE program
  ADD CONSTRAINT program_startyear_fk
  FOREIGN KEY(StartYear) REFERENCES SERIES(StartYear);

...it will will work.

Now if what you're really looking for is really a composite index, @Parado's answer is what you want, just wanted to point out that the index doesn't have to be composite.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top