Error creating mysql table with Foreign Key - mysql

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).

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.

trying to relate two table together

so pretty new to SQL I created 2 tables which I wanted to be related to one another but I'm getting an error "#1215 - Cannot add foreign key constraint" can someone point me to the right direction of this problem?
CREATE TABLE movie(
id INT(1) NOT NULL AUTO_INCREMENT,
nearname VARCHAR(25) NOT NULL,
release_date DATE NOT NULL,
lang VARCHAR(10) NOT NULL,
PRIMARY KEY(id),
CONSTRAINT same_movie FOREIGN KEY(id) REFERENCES movie_cast(movie_id)
);
CREATE TABLE movie_cast(
movie_id INT(1) NOT NULL AUTO_INCREMENT,
director_name VARCHAR(20) NOT NULL,
actor_name VARCHAR(20) NOT NULL,
actress_name VARCHAR(20) NOT NULL,
PRIMARY KEY(movie_id),
CONSTRAINT same_movie FOREIGN KEY(movie_id) REFERENCES movie(id)
);
You need to refer to the same column name as the primary key. In this case, it is called id:
CONSTRAINT same_movie FOREIGN KEY(movie_id) REFERENCES movie_cast(id)
Of course, your DDL doesn't define movie_cast. So, I am guessing the second table should be something like:
CREATE TABLE movie_cast (
id INT NOT NULL AUTO_INCREMENT,
movie_id int not null,
cast_name varchar(255)
PRIMARY KEY(id),
CONSTRAINT fk_movie_cast_movie FOREIGN KEY(movie_id) REFERENCES movie(movie_id)
);

errno: 150 "Foreign key constraint is incorrectly formed" Nothing helps

sorry for maybe stupid question, but I stack with my sql query. Tried out many methods to avid it but still have error 150. I've created 3 tables and one with foreighn keys:
Table users
create table users(
id int(11) primary key auto_increment,
unique_id varchar(23) not null unique,
name varchar(50) not null,
cname varchar(50) not null,
email varchar(100) not null unique,
encrypted_password varchar(80) not null,
salt varchar(10) not null,
created_at datetime,
updated_at datetime null
);
Table behaviours
CREATE TABLE behaviours (
id int(2) AUTO_INCREMENT PRIMARY KEY,
bName varchar(100) NOT NULL
);
Table severytys
CREATE TABLE severitys (
id int(2) AUTO_INCREMENT PRIMARY KEY,
severity varchar(10) NOT NULL
);
And here it shows errors:
CREATE TABLE child_behaviours(
id int(11) primary key auto_increment,
name varchar(50) not null,
cname varchar(50) not null,
bName varchar(100) NOT NULL,
severity varchar(10) NOT NULL,
start_at datetime,
stop_at datetime null,
FOREIGN KEY (id) REFERENCES users(id),
FOREIGN KEY (bName) REFERENCES behaviours(bName),
FOREIGN KEY (severity) REFERENCES severitys(severity)
);
Will be really pleasent to have an answer to this issue
You can only create a FK on a column that is both UNIQUE and NOT NULL. This is usually, but not always, the primary key of the referenced table.
If you reference anything other than the PK, you need a really really good reason.
(I'd even add to that, that you need a really really good reason to use anything other than an INT or a couple INTs as a PK...)
Now, child_behaviours has several errors:
Duplication of columns already present in users. If you reference users by its id, there is no need to duplicate the columns.
Reference to behaviors(bName) instead of using its id
same thing for reference to severity
Also, there is the generic mistake of using "id" columns. Please call them "user_id", "severity_id", etc, and then call them the same in your references. This will make your life much easier, and avoid stuff like:
SELECT foo.id AD foo_id, bar.id AS bar_id FROM foo JOIN bar ON ...
You have to refer to a primary key, when building a foreign key
CREATE TABLE child_behaviours(
userId int not null,
behaviourId int NOT NULL,
severityId int NOT NULL,
start_at datetime not null,
stop_at datetime,
FOREIGN KEY (userId) REFERENCES users(id),
FOREIGN KEY (behaviourId) REFERENCES behaviours(id),
FOREIGN KEY (severityId) REFERENCES severitys(id)
);

Why can't I add foreign key constraints

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.

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.