Why am I getting errors when trying to alter a table with a foreign key constraint?
I have 1 table, HSTORY
which I use as a base table for all other specific history tables (ie. USER_HISTORY
, BROWSER_HISTORY
, PICTURE_HISTORY
...). I have also included the PICTURE
and USER
tables as they get called as well.
HISTORY table:
CREATE TABLE IF NOT EXISTS HISTORY
(
ID INT NOT NULL AUTO_INCREMENT,
VIEWERID INT NOT NULL ,
VIEWDATE TIMESTAMP NOT NULL DEFAULT NOW(),
PRIMARY KEY (ID),
FOREIGN KEY (VIEWERID) REFERENCES USER(ID)
)
engine=innodb;
USER table: (in case anyone is curious)
CREATE TABLE IF NOT EXISTS USER
(
ID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY (ID)
)
engine=innodb;
PICTURE table: (in case anyone is curious)
CREATE TABLE IF NOT EXISTS PICTURE
(
ID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY (ID)
)
engine=innodb;
PICTURE_HISTORY table:
CREATE TABLE IF NOT EXISTS PICTURE_HISTORY LIKE HISTORY;
ALTER TABLE PICTURE_HISTORY
ADD FOREIGN KEY (FOREIGNID) REFERENCES PICTURE(ID);
However, when I do this, I get:
Key column 'FOREIGNID' doesn't exist in table
I take this to mean that I have to first create FOREIGNID
, but in many of the examples on SO, the above should work. Anyone know why this is occurring?
ALTER TABLE students ADD FOREIGN KEY (student_id) REFERENCES points(id); To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY constraint on multiple columns, use the following SQL syntax: ALTER TABLE students ADD CONSTRAINT fk_student_id FOREIGN KEY (student_id) REFERENCES points(id);
If you're altering an existing table with a new foreign key constraint, your database system will likely return an error if you attempt to create a foreign key constraint that links columns with different data types.
The usual cause are generally a mismatch in the type of the column of the primary table and the foreign table. It can also be a mismatch in the Engine type of two tables i.e. MyISAM or InnoDB. Datatype both columns should have same datatype. int(11) on one table and smallint(5) on another will cause problem.
It's a common mistake to avoid creating foreign keys in a database because they negatively impact the performance. It is true that foreign keys will impact INSERT, UPDATE and DELETE statements because they are data checking, but they improve the overall performance of a database.
Thanks to Michael for pointing out my mistake. I can't actually make a foreign key unless the column already exists. If instead I issue these two commands, the foreign key constraint is created:
ALTER TABLE PICTURE_HISTORY
ADD COLUMN FOREIGNID INT NOT NULL;
ALTER TABLE PICTURE_HISTORY
ADD FOREIGN KEY (FOREIGNID) REFERENCES PICTURE(ID);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With