sql - Oracle mySQL : Cannot add foreign key constraint -


i creating database table. code not add 2 foreign keys reason, says cannot add foreign key constraints, i'll show tables 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 means 1:n (one-to-many relationship). therefore, 2 primary keys in series become 2 foreign keys in program.

mysql> describe series; +------------+--------------+------+-----+---------+-------+ | field      | type         | null | key | default | | +------------+--------------+------+-----+---------+-------+ | 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 | | +-------------+--------------+------+-----+---------+-------+ | programname | varchar(50)  | no   | pri |         |       | | description | varchar(255) | yes  |     | null    |       | | recorded    | date         | no   |     | null    |       | +-------------+--------------+------+-----+---------+-------+ 3 rows in set (0.01 sec) 

you have composite pk on series table, can't use fields separately in fk constraint

 add constraint program_seriesname_fk  foreign key(seriesname, startyear) references series(seriesname, startyear) 

Comments

Popular posts from this blog

javascript - DIV "hiding" when changing dropdown value -

Does Firefox offer AppleScript support to get URL of windows? -

android - How to install packaged app on Firefox for mobile? -