I've been trying to connect my tables with with Foregin key, but I always get an error that my veriable does not exists. I set index for my primary key for counting. My code for table with primary key looks like this:
CREATE TABLE data_animal(
name VARCHAR(30) NOT NULL,
birth_date DATE NOT NULL,
sex ENUM('Male', 'Female') NOT NULL,
animal_car ENUM('Brave', 'Lazy', 'Agressive', 'Nice', 'Nervous') NOT NULL,
des VARCHAR (250),
type ENUM('Cat', 'Dog', 'Bird', 'Snake', 'Fish') NOT NULL,
steril ENUM('Yes', 'No') NOT NULL,
Breed VARCHAR(20) NOT NULL,
id_animal INT NOT NULL AUTO_INCREMENT PRIMARY KEY);
CREATE INDEX idx_id_animal
ON data_animal (id_animal);
My code for another table where I need id_animal as foregin key is:
CREATE TABLE photo(
id_picture INT AUTO_INCREMENT NOT NULL PRIMARY KEY,
FOREIGN KEY (id_animal) REFERENCES data_animal (id_animal)
);
I tried few defferent approaches how to insert foreign key as:
id_animal int FOREIGN KEY REFERENCES data_animal(id_animal)
or
CREATE TABLE photo(
id_picture INT AUTO_INCREMENT NOT NULL PRIMARY KEY,
FOREIGN KEY (id_animal) REFERENCES data_animal (id_animal)
)ENGINE=INNODB;
or
CONSTRAINT data_animal FOREIGN KEY (id_animal)
REFERENCES data_animal(id_animal)
I always get this error:
(Key column 'id_animal' doesn't exist in table)
I don't know what else could be wrong. Thanks for the help.
The foreign key has to be a column in the table you're defining, so you need to add an id_animal column to the photos table before you can make it a foreign key.
CREATE TABLE photo(
id_picture INT AUTO_INCREMENT NOT NULL PRIMARY KEY,
id_animal INT,
FOREIGN KEY (id_animal) REFERENCES data_animal (id_animal)
);
Related
CREATE TABLE employee(
empid int auto_increment primary key,
empfirstname varchar(200) not null,
emplastname varchar(200) not null,
email varchar(200) not null,
officenumber int not null
);
CREATE TABLE customer(
custid int auto_increment primary key,
firstname varchar(200) not null,
lastname varchar(200) not null,
address varchar(200) not null,
contact varchar(200)
);
CREATE TABLE product(
productid int auto_increment primary key,
productdesc varchar(500) not null,
weight int not null,
unit_cost int not null
);
CREATE TABLE productorder(
productid int,
orderid int,
primary key(productid,orderid),
constraint fk3 foreign key (productid) references product(productid),
constraint fk4 foreign key (orderid) references productorder(orderid)
);
CREATE TABLE salesorder(
salesorderid int auto_increment primary key,
empid int not null,
custid int not null,
orderdate date not null,
shippingmethod varchar (200) not null,
constraint a_fk1 foreign key (empid) references employee(empid),
constraint a_fk2 foreign key (custid) references customer(custid)
);
What is this meant to do?:
constraint fk4 foreign key (orderid) references productorder(orderid)
It's not uncommon for a table to have a foreign key back to its own primary key, such as for records which have a parent/child relationship. But that doesn't seem to be the case here.
More to the point of the error though, this isn't referencing the entire primary key for the target table. That key has two fields:
primary key(productid,orderid)
So the DBMS can't create the foreign key because its structure doesn't match the target primary key.
If you want to create that foreign key, it would need to match. Probably something like this:
constraint fk4 foreign key (productid,orderid) references productorder(productid,orderid)
But it doesn't appear that you need that foreign key at all, because it doesn't seem to make sense in your data model. Instead I suspect orderid might need to be autoincrement and just use the productid foreign key. Something like this:
CREATE TABLE productorder(
orderid int auto_increment primary key,
productid int,
constraint fk3 foreign key (productid) references product(productid)
);
(Note that there could be more changes you'd want to make to your data model. This answer doesn't purport to provide you with a complete production-ready data model, just to correct the error. Your data model is likely to change/evolve as you develop your system.)
Its normal,
The foreign key in table **productorder**
is refereing to the table itself:
constraint fk4 foreign key (orderid) references **productorder**(orderid)
In order to achieve the self-referencing constraint on the table productorder, you need to add another column with the same type and make typical referencing.
For instance :
Create table productorder (
productid int,
orderid int,
orderid_parent int,
primary key(productid,orderid),
constraint fk_self foreign key(orderid) references productorder(orderid_parent)
)
Getting an
Error Code: 1822. Failed to add the foreign key constraint. Missing
index for constraint 'subject_ibfk_1' in the referenced table
'enrolment'
when attempting to create the subject table. The problem is, the error does not occur on the previous table student. The data types are the same, and the primary keys are defined.
This error occurs for both the enrolment and grade tables.
create table enrolment(
stud_id char(9) not null,
subj_code char(8) not null,
semester tinyint unsigned not null,
year smallint unsigned not null,
comment text,
primary key (stud_id, subj_code, semester, year)
);
create table grade(
stud_id char(9) not null,
subj_code char(8) not null,
semester tinyint unsigned not null,
year smallint unsigned not null,
grade tinyint unsigned,
primary key (stud_id, subj_code, semester, year)
);
create table student(
stud_id char(9) not null,
stud_name char(30),
stud_phone char(12),
stud_date_of_birth date,
stud_city char(26),
stud_address char(30),
stud_postcode char(4),
primary key (stud_id),
foreign key (stud_id)
references grade(stud_id),
foreign key (stud_id)
references enrolment(stud_id)
);
create table subject(
subj_code char(8) not null,
subj_title char(40),
primary key (subj_code),
foreign key (subj_code)
references enrolment(subj_code),
foreign key (subj_code)
references grade(subj_code)
);
The problem is due to the fact that the foreign key, subj_code, is part of a multi-column primary key (PK) in the referenced table enrolment:
primary key (stud_id, subj_code, semester, year)
where this column (subj_code) is not the leftmost one.
Table student does not have this problem because its foreign key column stud_id is the leftmost column of the PK in the referenced table.
To resolve this you can create a new index for the referened column:
ALTER TABLE enrolment ADD INDEX subj_code_idx (subj_code);
Note: You have to do the same for referenced table grade in the other foreign key.
Demo here
FOREIGN KEY of one table is a PRIMARY key of another table. its a mapping key or column between two table.
First of all: you don't make subject_id as primary key in CLO table.
subject_id is act as a primary key in subject table and foreign key in clo table
ALTER TABLE `clo` DROP PRIMARY KEY, ADD PRIMARY KEY(`clo_id`);
ALTER TABLE `subject` DROP PRIMARY KEY, ADD PRIMARY KEY(`subject_id`);
ALTER TABLE clo ADD FOREIGN KEY (subject_id) REFERENCES subject(subject_id)
This is the exact error that WAMP returns when I run the child code from an external file called entries.txt
ERROR 1215 (HY000): Can not Add External Index Constraints
I need to be able to connect the parent tables to the child table so that links can be made between the tables easily.
The question states:
Create and populate a third table called entries, again using query scripts.
This table should contain foreign keys to allow sensible links to be
made with the other two tables, together with the dates of each exam.
Parent Tables:
CREATE TABLE IF NOT EXISTS students(
student_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
first_name VARCHAR(20) NOT NULL,
middle_name VARCHAR(20),
last_name VARCHAR(40) NOT NULL,
email VARCHAR(60) NOT NULL,
password CHAR(40) NOT NULL,
reg_date DATETIME NOT NULL,
PRIMARY KEY (student_id),
UNIQUE (email));
CREATE TABLE IF NOT EXISTS subjects(
subject_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
subject_name CHAR(30) NOT NULL,
level_of_entry VARCHAR(10) NOT NULL,
exam_board CHAR(20) NOT NULL,
PRIMARY KEY (subject_id));
Child Table:
CREATE TABLE IF NOT EXISTS entries(
date_of_exam DATETIME NOT NULL,
first_name VARCHAR,
middle_name VARCHAR,
last_name VARCHAR,
subject_name CHAR,
level_of_entry VARCHAR,
exam_board CHAR,
INDEX idx_first_name(first_name),
INDEX idx_middle_name(middle_name),
INDEX idx_last_name(last_name),
INDEX idx_subject_name(subject_name),
INDEX idx_level_of_entry(level_of_entry),
INDEX idx_exam_board(exam_board),
PRIMARY KEY (date_of_exam),
CONSTRAINT fk_first_name FOREIGN KEY (first_name) REFERENCES students(first_name),
CONSTRAINT fk_middle_name FOREIGN KEY (middle_name) REFERENCES students(middle_name),
CONSTRAINT fk_last_name FOREIGN KEY (last_name) REFERENCES students(last_name),
CONSTRAINT fk_subject_name FOREIGN KEY (subject_name) REFERENCES subjects(subject_name),
CONSTRAINT fk_level_of_entry FOREIGN KEY (level_of_entry) REFERENCES subjects(level_of_entry),
CONSTRAINT fk_exam_board FOREIGN KEY (exam_board) REFERENCES subjects(exam_board)
)ENGINE=InnoDB;
A foreign key in the child table must reference the primary key of the parent table only. You don't need to create clones of every attribute column of the parent tables, just the primary key column. If you need to read the other attributes, you'd write a query with a JOIN.
CREATE TABLE IF NOT EXISTS entries(
student_id INT UNSIGNED NOT NULL,
subject_id INT UNSIGNED NOT NULL,
date_of_exam DATETIME NOT NULL,
PRIMARY KEY (student_id, subject_id, date_of_exam),
CONSTRAINT fk_student FOREIGN KEY (student_id) REFERENCES students(student_id),
CONSTRAINT fk_subject FOREIGN KEY (subject_id) REFERENCES subjects(subject_id),
)ENGINE=InnoDB;
I have 3 table: CD, Song and Song_Details which is a relationship between CD & Song:
create table Song(
ID int not null auto_increment,
Title varchar(255) not null,
Length float not null,
primary key (ID, Title)
);
create table CD(
Title varchar(255) not null,
CD_Number int not null,
primary key (Title, CD_Number)
);
Create table Song_Details(
CD_Title varchar(255) not null,
Song_Title varchar(255) not null,
Track_Number int not null,
primary key(CD_Title, Song_Title),
foreign key(CD_Title) references CD(Title),
foreign key(Song_Title) references Song(Title)
);
I have managed to find out that this line in Song_Details:
foreign key(Song_Title) references Song(Title) is throwing the Error 1215(HY000): Cannot add foreign key constraint;
Could anyone help me see based on my table, what could be causing this issue?
Two things. The auto_increment key would normally be the foreign key. Second, you need to make your reference to all the keys defined as the primary or unique key for the table (I don't advise making foreign key references to non-unique keys although MySQL does all that).
So:
create table Song (
Song_ID int not null auto_increment,
Title varchar(255) not null,
Length float not null,
primary key (ID),
unique (title)
);
create table CD (
CD_Id int auto_increment primary key,
Title varchar(255) not null,
CD_Number int not null,
unique (Title, CD_Number)
);
Create table Song_Details(
CD_ID varchar(255) not null,
Song_Id varchar(255) not null,
Track_Number int not null,
primary key(CD_ID, Song_ID),
foreign key(CD_ID) references CD(CD_ID),
foreign key(Song_ID) references Song(Song_ID)
);
Notes:
Use the primary key relationships for the foreign key definitions.
I like to have the primary keys include the table name. That way, the primary key can have the same name as the corresponding foreign keys.
Don't put the titles in more than one place. They belong in the entity tables. Autoincremented ids can then be used to access the titles.
Ok, maybe it's late and I'm being stupid, but I can't seem to figure out why I'm getting a Cannot add Foreign Key Constraint error for the following query
DROP TABLE IF EXISTS People_Lordships;
CREATE TABLE People_Lordships
(
Id INT PRIMARY KEY AUTO_INCREMENT,
PersonId INT NOT NULL,
LordshipId INT NOT NULL,
AssumedDate Date,
AbdicatedDate Date
);
DROP TABLE IF EXISTS People_Lordships_Current;
CREATE TABLE People_Lordships_Current
(
Id INT PRIMARY KEY AUTO_INCREMENT,
People_LordshipsId INT NOT NULL,
LordShipId INT NOT NULL,
CONSTRAINT Fk_People_Lordships_Current_People_LordshipsId_LordshipId
FOREIGN KEY (`LordshipId`,`People_LordshipsId`)
REFERENCES People_Lordships (`LordshipId`,`Id`)
ON DELETE RESTRICT ON UPDATE CASCADE,
CONSTRAINT UQ_People_Lordships_Current_LordshipId
UNIQUE KEY (`LordshipId`)
);
And yes, it is a database about noble titles... it's a long story
There is no column LordshipId in table People_Lordships.
Your foreign key definition attempts to reference a column that doesn't exist.
REFERENCES People_Lordships (`LordshipId`,`Id`)
^^^^^^^^^^^^
Figured this one out.
It turns out MySQL cannot add a foreign key constraint against a column that is not the first column in an index.
The following will work
DROP TABLE IF EXISTS People_Lordships;
CREATE TABLE People_Lordships
(
Id INT PRIMARY KEY AUTO_INCREMENT,
PersonId INT NOT NULL,
LordshipId INT NOT NULL,
AssumedDate Date,
AbdicatedDate Date,
INDEX Idx_LordshipId (LordshipId)
);
DROP TABLE IF EXISTS People_Lordships_Current;
CREATE TABLE People_Lordships_Current
(
Id INT PRIMARY KEY AUTO_INCREMENT,
People_LordshipsId INT NOT NULL,
LordShipId INT NOT NULL,
CONSTRAINT Fk_People_Lordships_Current_People_LordshipsId_LordshipId
FOREIGN KEY (`LordshipId`,`People_LordshipsId`)
REFERENCES People_Lordships (`LordshipId`,`Id`)
ON DELETE RESTRICT ON UPDATE CASCADE,
CONSTRAINT UQ_People_Lordships_Current_LordshipId
UNIQUE KEY (`LordshipId`)
);