Why can't I add foreign key constraints - mysql

this is my code:
CREATE DATABASE exams;
SHOW DATABASES;
CREATE TABLE IF NOT EXISTS students(
student_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
first_name VARCHAR(20) NOT NULL,
middle_name VARCHAR(40),
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));
SHOW table status
INSERT INTO exams_3121(student_id, first_name, middle_name, last_name, email, password, reg_date)
CREATE TABLE entries
(
entrie_id int NOT NULL,
student_id int NOT NULL,
subject_id int,
PRIMARY KEY (entrie_id),
FOREIGN KEY (student_id) REFERENCES student(student_id),
FOREIGN KEY (subject_id)REFERENCES subject(subject_id)
)
CREATE DATABASE subjects;
CREATE TABLE IF NOT EXISTS subjects(
subject_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
subject_name VARCHAR(20) NOT NULL,
level_entery VARCHAR(40)NOT NULL,
exam_board VARCHAR(60) NOT NULL,
PRIMARY KEY (subject_id));
CREATE TABLE entries
(
entrie_id int NOT NULL,
entrie_id int NOT NULL,
subject_id int,
PRIMARY KEY (entrie_id),
FOREIGN KEY (student_id) REFERENCES student(student_id),
FOREIGN KEY (subject_id)REFERENCES subject(subject_id)
)
When I use this code it says cannot add foreign key constraint
and I don't know what to do. Please and thanks in advance.

There are two problems.
First, you got the names of the table you're referencing wrong. The name of the tables are students and subjects, but you wrote student and subject.
Second, the entries table has two entrie_id columns. One of them should be student_id.
CREATE TABLE entries
(
entrie_id int NOT NULL,
student_id int NOT NULL,
subject_id int,
PRIMARY KEY (entrie_id),
FOREIGN KEY (student_id) REFERENCES students(student_id),
FOREIGN KEY (subject_id) REFERENCES subjects(subject_id)
)
Also, if you're creating multiple databases and putting your tables in them, you'll need to refer to tables with their database prefixes if they're different from the one you selected as default with the USE command. As you've written it, you're not actually using the databases you created with CREATE DATABASE.

Related

Why does it fail to open the referenced table if it already exists?

Somehow I can't create a join table for two entities I already have.
Here is what I run on MySQL just fine, the last one is the one I'm struggling with.
create table instructor_detail_table(
instructor_detail_id int not null primary key auto_increment,
instructor_class varchar(40) not null
);
create table instructor_table(
instructor_id int not null primary key auto_increment,
instructor_name varchar(40) not null,
instructor_detail_id int not null,
foreign key (instructor_detail_id) references instructor_detail_table (instructor_detail_id)
);
create table course_table(
course_id int not null primary key auto_increment,
course_class varchar(40) not null,
instructor_id int not null,
foreign key (instructor_id) references instructor_table (instructor_id)
);
create table student_table(
student_id int not null primary key auto_increment,
student_name varchar(40) not null,
student_age int not null
);
create table student_course_table(
student_id int not null,
course_id int not null,
foreign key (student_id) references student_table (student_id),
foreign key (course_id) references course_table (course_id),
primary key (student_id, course_id)
);
When I try to create the student_course_table MySQL complaints it can't open the referenced table student_table
Thanks in advance
You can have this problem if the storage engine is not the good one.
For example 'MyISAM' instead of 'InnoDB' for the table 'student_table'.
Because MyISAM doesn't support foreign key.

MYSQL Foreign key incorrectly formed

Have an error where my first foreign key constraint is incorrectly formed. I'm waiting to hear back from my lecturer if she can spot the issue but thought I'd ask here
My SQL query is as follows
CREATE DATABASE rugby;
USE rugby;
CREATE TABLE address(
address_ID INT AUTO_INCREMENT NOT NULL,
address_name VARCHAR(50) NOT NULL,
PRIMARY KEY (address_ID)
) ENGINE=INNODB;
CREATE TABLE team(
team_ID INT AUTO_INCREMENT NOT NULL,
team_Name VARCHAR(25) NOT NULL,
team_Year INT NOT NULL,
PRIMARY KEY(team_ID)
) ENGINE=INNODB;
CREATE TABLE person(
person_ID INT AUTO_INCREMENT NOT NULL,
name VARCHAR(30) NOT NULL,
phone INT NOT NULL,
address_ID INT NOT NULL,
email VARCHAR(50),
photo BLOB,
PRIMARY KEY(person_ID),
FOREIGN KEY(address_ID) REFERENCES address(address_ID) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=INNODB;
I have followed how we were taught but can't spot the issue.
Any help appreciated
In table person you have defined address_ID as NOT NULL, but
when you define the FOREIGN KEY you set:
ON DELETE SET NULL
which contradicts the NOT NULL definition.

Error creating mysql table with Foreign Key

I have researched thoroughly before asking this question including on this site.
I have a students table:
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));
I also have a subjects table:
CREATE TABLE IF NOT EXISTS subjects(
subject_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
subject_name VARCHAR(40) NOT NULL,
level_of_entry VARCHAR(20) NOT NULL,
exam_board VARCHAR(20) NOT NULL,
PRIMARY KEY (subject_id));
I am now creating a table to link the above tables:
CREATE TABLE IF NOT EXISTS entries(
exam_date DATETIME NOT NULL,
FOREIGN KEY (student_id) REFERENCES students (student_id),
FOREIGN KEY (subject_id) REFERENCES subjects (subject_id)
);
My problem is that when I try to declare the foreign keys in the third table called entries, I get an error stating that the subject_id foreign key is not in the table referenced.
ERROR 1072 (42000) : Key column 'student_id' doesn't exist in table, even though it is clearly contained inside the the students table and the same applies to 'subject_id' and the subject table.
I am certain that my syntax for declaring the foreign keys is correct so I am unsure how to fix the problem.
All help is appreciated. Thank you.
You forgot to create these two columns before applying your foreign key constraints :
CREATE TABLE IF NOT EXISTS entries(
exam_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
student_id INT UNSIGNED NOT NULL,
subject_id INT UNSIGNED NOT NULL,
exam_date DATETIME NOT NULL,
PRIMARY KEY (exam_id),
FOREIGN KEY (student_id) REFERENCES students (student_id),
FOREIGN KEY (subject_id) REFERENCES subjects (subject_id)
);
EDIT :
I advise you to add in every table a unique ID column (here : exam_id).

Cannot add or update a child row: foreign key constraint fails

Hi I am wondering why I getting an error
ERROR 1452 (23000): Cannot add or update a child row: a foreign key
constraint fails (exams.entries, CONSTRAINT entries_ibfk_2
FOREIGN KEY (student_id) REFERENCES students (student_id))
Any help would be appriatiated!
Here are the scripts that I think are relevant to the problem I'm having,
First I made this table entries and everything was fine
CREATE TABLE entries(
subject_id INT UNSIGNED NOT NULL,
subject_name VARCHAR(60) NOT NULL,
level_of_entry VARCHAR(60) NOT NULL,
exam_board VARCHAR(60) NOT NULL,
student_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
date_of_exam DATETIME NOT NULL,
PRIMARY KEY (date_of_exam),
FOREIGN KEY (subject_id)
REFERENCES subjects(subject_id),
FOREIGN KEY (student_id)
REFERENCES students(student_id)
Then I tried to insert data and I got the error.
INSERT INTO entries (subject_id,subject_name, level_of_entry, exam_board,date_of_exam)
VALUE ('1','chemistry','as','ocr','2017-05-05 12:00:00'),
('2','biology','gcse','aqa','2017-05-05 12:00:01'),
('3','music','gcse','edexcel','2017-05-05 12:00:02'),
('4','english','a','ocr','2017-05-05 12:00:03'),
('5','physics','a','aqa','2017-05-05 12:00:04'),
('6','maths','gcse','aqa','2017-05-05 12:00:05'),
('7','computing','gcse','aqa','2017-05-05 12:00:06'),
('8','physical_education','gcse','aqa','2017-05-05 12:00:07'),
('9','design_and_technology','gcse','aqa','2017-05-05 12:00:08'),
('10','french','gcse','aqa','2017-05-05 12:00:09');
It suggest on other questions similar to this to make sure your parent table has the same values but it does and its making know sense to me.
Here is the parent script.
CREATE TABLE IF NOT EXISTS students(
student_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
first_name VARCHAR(20) NOT NULL,
middle_name VARCHAR(20) NOT NULL,
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));
Here is the other parent script but I'm having no problems with it.
CREATE TABLE IF NOT EXISTS subjects(
subject_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
subject_name VARCHAR(60) NOT NULL,
level_of_entry VARCHAR(60) NOT NULL,
exam_board VARCHAR(60) NOT NULL,
PRIMARY KEY (subject_id) ,
UNIQUE (subject_id));
If anyone could help I would be extremely grateful!
There are two issues with your logic related to student_id.
You should not have AUTO_INCREMENT in foreign key table.
A table which has a foreign key can't auto-populate values (logically and technically). It has to refer to some value in its Primary table. In your case, it is students table.
So, change your table structure as below:
CREATE TABLE entries(
subject_id INT UNSIGNED NOT NULL,
subject_name VARCHAR(60) NOT NULL,
level_of_entry VARCHAR(60) NOT NULL,
exam_board VARCHAR(60) NOT NULL,
student_id INT UNSIGNED NOT NULL,
date_of_exam DATETIME NOT NULL,
PRIMARY KEY (date_of_exam),
FOREIGN KEY (subject_id)
REFERENCES subjects(subject_id),
FOREIGN KEY (student_id)
REFERENCES students(student_id)
You should specify a value in your INSERT query for entries table
You need to ensure you insert a value manually in your entries table for student_id column.
A side not as specified in comments that you defined subject_id as INT but you are trying to insert character values.
Change your insert query as below:
INSERT INTO entries (subject_id,subject_name, level_of_entry, exam_board,date_of_exam, student_id)
VALUE (1,'chemistry','as','ocr','2017-05-05 12:00:00', 100),
(2,'biology','gcse','aqa','2017-05-05 12:00:01', 101);
Note: I assumed 100 and 101 as your existing student ids from students table. You need to replace them with the correct ids from your table.

#1005 - Can't create table on ALTER TABLE when connecting table via FOREIGN KEY

I am working on a homework assignment. I have to build a database for a video store. All of the following works:
CREATE TABLE Stock
(
PKStock_ID VARCHAR(8) NOT NULL,
FKTitle VARCHAR(8) NOT NULL,
NoOfDVD INT(10) NOT NULL,
NoOfVHS INT(10) NOT NULL,
PRIMARY KEY (PKStock_ID)
);
CREATE TABLE Inventory
(
PKUnique_ID VARCHAR(8) NOT NULL,
DistributorSerialNo VARCHAR(8) NOT NULL,
Distributor_ID VARCHAR(8) NOT NULL,
FKTitle_ID VARCHAR(8) NOT NULL,
InStock CHAR(1) NOT NULL,
DateOut TIMESTAMP,
DateBack TIMESTAMP,
Customer_ID VARCHAR(8) NOT NULL,
Rental_Price DECIMAL(4,2) NOT NULL,
PRIMARY KEY (PKUnique_ID)
);
CREATE TABLE Movie
(
PKTitle_ID VARCHAR(8) NOT NULL,
FKTitle_ID VARCHAR(8) NOT NULL,
Title VARCHAR(30),
Genre VARCHAR(8),
YearReleased INT,
Length INT,
PRIMARY KEY (PKTitle_ID)
);
CREATE TABLE Actors
(
PKActor_ID VARCHAR(8) NOT NULL,
FKActor_ID VARCHAR(8) NOT NULL,
Actors VARCHAR(30),
PRIMARY KEY (PKActor_ID)
);
CREATE TABLE Awards
(
PKAward_ID VARCHAR(8) NOT NULL,
FKAward_ID VARCHAR(8) NOT NULL,
Awards VARCHAR(30),
PRIMARY KEY (PKAward_ID)
);
CREATE TABLE Directors
(
PKDirector_ID VARCHAR(8) NOT NULL,
FKDirector_ID VARCHAR(8) NOT NULL,
Directors VARCHAR(30),
PRIMARY KEY (PKDirector_ID)
);
CREATE TABLE ElectronicCatalogue
(
PKElectronicCatalogue VARCHAR(8) NOT NULL,
FKDistributor_ID VARCHAR(8) NOT NULL,
DistributorSerialNo VARCHAR(8) NOT NULL,
Price DECIMAL(6,2) NOT NULL,
PRIMARY KEY (PKElectronicCatalogue)
);
CREATE TABLE Distributors
(
PKDistributor_ID VARCHAR(8) NOT NULL,
FKDistributor_ID VARCHAR(8) NOT NULL,
NameOfDistributer VARCHAR(30) NOT NULL,
Horror CHAR(1) NOT NULL,
Drama CHAR(1) NOT NULL,
Comedy CHAR(1) NOT NULL,
Action CHAR(1) NOT NULL,
Thrillers CHAR(1) NOT NULL,
PRIMARY KEY (PKDistributor_ID)
);
CREATE TABLE Customers
(
PKCustomer_ID VARCHAR(8) NOT NULL,
FKUnique_ID VARCHAR(8) NOT NULL,
Name VARCHAR(30),
Address VARCHAR(100),
Phone INT NOT NULL,
PRIMARY KEY (PKCustomer_ID)
);
CREATE TABLE Fees
(
PKFee_ID VARCHAR(8) NOT NULL,
FK_ID VARCHAR(8) NOT NULL,
Damages DECIMAL(10,2) NOT NULL,
Late DECIMAL(10,2) NOT NULL,
PRIMARY KEY (PKFee_ID)
);
ALTER TABLE Stock
ADD FOREIGN KEY (FKTitle)
REFERENCES Inventory(PKUnique_ID);
ALTER TABLE Movie
ADD FOREIGN KEY (FKTitle_ID)
REFERENCES Stock (PKStock_ID);
ALTER TABLE Actors
ADD FOREIGN KEY (FKActor_ID)
REFERENCES Movie (PKTitle_ID);
ALTER TABLE Awards
ADD FOREIGN KEY (FKAward_ID)
REFERENCES Movie (PKTitle_ID);
ALTER TABLE Directors
ADD FOREIGN KEY (FKDirector_ID)
REFERENCES Movie (PKTitle_ID);
ALTER TABLE ElectronicCatalogue
ADD FOREIGN KEY (FKDistributor_ID)
REFERENCES Inventory (PKUnique_ID);
ALTER TABLE Distributors
ADD FOREIGN KEY (FKDistributor_ID)
REFERENCES ElectronicCatalogue (PKElectronicCatalogue);
I next want to connect the Inventory table to the customers table. When I do the following:
ALTER TABLE Customers
ADD FOREIGN KEY (FKUnique_ID)
REFERENCES Inventory (Customer_ID);
I get this error:
#1005 - Can't create table 'mm.#sql-9f69_110' (errno: 150)
What am I doing wrong?
Foreign key should point to a unique column (primary key or unique). Your Inventory (Customer_ID) is not unique.
I think you are trying to :
ALTER TABLE Inventory
ADD CONSTRAINT fk1_Inv FOREIGN KEY (Customer_ID)
REFERENCES Customers (PKCustomer_ID);
Not sure why you didn't get the full message but there's a command line tool bundled with MySQL that provides further information about cryptic error messages like this (or you can just Google for the error code):
C:>perror 150
MySQL error code 150: Foreign key constraint is incorrectly formed
If you have the SUPER privilege, you can get further details with this query:
show engine innodb status
And in this case you see this:
LATEST FOREIGN KEY ERROR
------------------------
130226 21:00:25 Error in foreign key constraint of table test/#sql-1d98_1:
FOREIGN KEY (FKUnique_ID)
REFERENCES Inventory (Customer_ID):
Cannot find an index in the referenced table where the
referenced columns appear as the first columns, or column types
in the table and the referenced table do not match for constraint.
Note that the internal storage type of ENUM and SET changed in
tables created with >= InnoDB-4.1.12, and such columns in old tables
cannot be referenced by such columns in new tables.
See http://dev.mysql.com/doc/refman/5.0/en/innodb-foreign-key-constraints.html
for correct foreign key definition.
So you are missing an index as explained.
Edit: As other answers point out, if there's no index it's because you're linking to the wrong column.
As Álvaro G. Vicario says you are missing an index, this is because you are not correctly using foreign keys.
ALTER TABLE Customers
ADD FOREIGN KEY (FKUnique_ID)
REFERENCES Inventory (Customer_ID);
This should be:
ALTER TABLE Inventory
ADD FOREIGN KEY (Customer_ID)
REFERENCES Customer(PKCustomer_ID);
The foreign key checks if the customer in the Inventory table actually exists in the Customers table. Thus Inventory here is the table you want to add the foreign key too and it references in primary key in the Customer table.
What you are trying to do is reference the Customer_ID in Inventory, which is just an VARCHAR(8)column and not an Primary Key (Index).
You should double check your other alter statements as well.
This turns out that you have different collation settings between these tables. In my case we had latin_swedish_ci and utf8_general_ci