trying to relate two table together - mysql

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

Related

Error Code: 1822. Failed to add the foreign key constraint. Missing index for constraint 'client_fk_name' in the referenced table 'client'

Why am I unable to add these foreign keys?
I'm trying to make clientName and employeeId both foreign keys in the events table. I realize I may not need clientEmail, but my error is currently showing at clientName.
CREATE TABLE client
(
clientName VARCHAR(50) PRIMARY KEY NOT NULL,
clientID INT NOT NULL auto_increment,
clientEmail VARCHAR(50) NOT NULL,
clientPass VARCHAR(50) NOT NULL,
phone VARCHAR(50) NOT NULL
);
CREATE TABLE admin
(
Name VARCHAR(50) NOT NULL,
adminId INT NOT NULL PRIMARY KEY auto_increment,
adminPass VARCHAR(50) NOT NULL,
adminEmail VARCHAR(50) NOT NULL
);
CREATE TABLE employee
(
Name VARCHAR(50) NOT NULL,
employeeId INT NOT NULL PRIMARY KEY auto_increment,
employeePass VARCHAR(50) NOT NULL,
employeeEmail VARCHAR(50) NOT NULL
);
CREATE TABLE event
(
eventId INT PRIMARY KEY auto_increment,
employeeId INT NOT NULL,
clientName VARCHAR(50) NOT NULL,
clientEmail VARCHAR(50) NOT NULL,
Constraint client_fk_name
Foreign Key (clientName)
references client (clientName),
Constraint client_fk_email
Foreign Key (clientEmail)
references client (clientEmail),
Constraint employee_fk_id
Foreign Key (employeeId)
references employee (employeeId)
);
Only these four tables.
So, one way to deal with this is to call the attribute in the parent table UNIQUE. This solves this error. However, as a side effect in my current experience, upon inserting into the database you may experience problems if your values are not unique (possibly obviously). But if you can guarantee uniqueness then just add Unique and you will be fine.
Unique specifies an attribute as a candidate key. Essentially it’s saying this could have been the primary key, but we chose something else.

Why do I have error code:1822 when my foreign key index matches the primary key in the table it is being referenced? [duplicate]

This question already has answers here:
MySQL Creating tables with Foreign Keys giving errno: 150
(20 answers)
Closed 1 year ago.
create table item
(
isbn varchar(25) not null,
title varchar(150) not null,
publisher_name varchar(50) not null,
classification_code varchar(10) not null,
format_type char(2),
constraint item_pk primary key(isbn)
);
create table copy
(
isbn varchar(25) not null,
copy_id int not null,
acquired_date not null,
constraint copy_pk primary key(isbn, copy_id),
constraint copy_fk foreign key(isbn) references item(isbn)
);
create table borrow (
isbn varchar(25) not null,
copy_id int not null,
user_id varchar(25) not null,
borrowed_datetime datetime not null,
returned_datetime datetime not null,
constraint borrow_pk primary key (isbn, copy_id, user_id, borrowed_datetime),
constraint borrow_fk_1 foreign key(isbn) references copy(isbn),
constraint borrow_fk_2 foreign key(copy_id) references copy(copy_id),
);
So this is my code here from MySQL and every time I try to run it, only Tables item and copy is created. Table borrow is not created due to "Error Code: 1822. Failed to add the foreign key constraint. Missing index for constraint 'borrow_fk_2' in the referenced table 'copy'".
My search engine is InnoDB.
To reference a compound primary key, you must declare a foreign key with the same number of columns as the primary key, and in the same order. In your case, you need the foreign key to be (isbn, copy_id) like this:
create table borrow (
isbn varchar(25) not null,
copy_id int not null,
user_id varchar(25) not null,
borrowed_datetime datetime not null,
returned_datetime datetime not null,
constraint borrow_pk primary key (isbn, copy_id, user_id, borrowed_datetime),
constraint borrow_fk_1 foreign key(isbn, copy_id) references copy(isbn, copy_id)
);

MySQL Error - Cannot add foreign key constraint

I know this question has been asked several times but it seemed like the problem was due to different data types between parent and child rows.
In my case, the data types are the same but I'm still getting the error. Here's my code
CREATE TABLE STUDENT_2(
StudentNumber INT NOT NULL AUTO_INCREMENT,
StudentName VARCHAR(50) NULL,
Dorm VARCHAR(50) NULL,
RoomType VARCHAR(50) NOT NULL,
CONSTRAINT STUDENTPK PRIMARY KEY(StudentNumber)
);
CREATE TABLE DORM_COST(
RoomType VARCHAR(50) NOT NULL,
DormCost DECIMAL(7,2) NULL,
CONSTRAINT DORM_COSTPK PRIMARY KEY(RoomType),
CONSTRAINT DORM_COST_FK FOREIGN KEY(RoomType)
REFERENCES STUDENT_2(RoomType)
ON UPDATE CASCADE
ON DELETE CASCADE
);
Where DORM_COSTS' foreign key cannot be added.
Thanks!
You want the foreign key reference on the table that has the foreign key, not the primary key. So, that would be:
CREATE TABLE DORM_COST (
RoomType VARCHAR(50) NOT NULL,
DormCost DECIMAL(7,2) NULL,
CONSTRAINT DORM_COSTPK PRIMARY KEY(RoomType)
);
CREATE TABLE STUDENT_2(
StudentNumber INT NOT NULL AUTO_INCREMENT,
StudentName VARCHAR(50) NULL,
Dorm VARCHAR(50) NULL,
RoomType VARCHAR(50) NOT NULL,
CONSTRAINT STUDENTPK PRIMARY KEY(StudentNumber),
CONSTRAINT fk_student2_roomtype FOREIGN KEY (RoomType) REFERENCES DORM_COST(RoomType)
);
Here is a db<>fiddle that shows that this works.
That said your data model seems quite strange.
I would expect a table called RoomTypes to have a primary key of RoomTypeId.
I would expect dorm_cost to have dates, because costs can vary from year to year.
I would expect different dorms to have similar room types -- singles, doubles, and so on.
I would expect those room types to vary, perhaps, by dorm.

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

Foreign key error

why the foreign key gives my headache?
first i created database names colorcode then paper table which works fine:
CREATE TABLE paper (
paper_id int(20) NOT NULL,
description VARCHAR(40) NOT NULL,
paper_color VARCHAR(40) NOT NULL,
PRIMARY KEY (paper_id, paper_color)
) ENGINE=InnoDB;
then brick table
CREATE TABLE brick(
brick_id int(20) NOT NULL,
description varchar(40) NOT NULL,
brick_color varchar (40) NOT NULL,
PRIMARY KEY (brick_id),
FOREIGN KEY (brick_color) REFERENCES paper(paper_color)
) ENGINE=InnoDB;
which doesn't=>
#1005 - Can't create table 'colorcode.brick' (errno: 150)
thank you for your help
create table paper (
paper_id int(20) not null,
description VARCHAR(40)not null,
paper_color VARCHAR(40) NOT NULL,
primary key (paper_id, paper_color),
INDEX(`paper_color`)
)engine=InnoDB;
create table brick (
brick_id int(20) not null,
description varchar(40) not null,
brick_color varchar (40) not null,
primary key (brick_id),
CONSTRAINT foreign key (`brick_color`) REFERENCES paper(`paper_color`)
)engine=InnoDB;
Demo: http://sqlfiddle.com/#!2/316d9
InnoDB permits a foreign key to reference any index column or group of
columns. However, in the referenced table, there must be an index
where the referenced columns are listed as the first columns in the
same order.
http://dev.mysql.com/doc/refman/5.6/en/innodb-foreign-key-constraints.html
"paper_color" has to be an index in order to reference.
Hope this helps.
Create a separate key for paper_color and it will work:
CREATE TABLE paper (
paper_id int(20) not null,
description VARCHAR(40)not null,
paper_color VARCHAR(40) NOT NULL,
PRIMARY KEY (paper_id, paper_color),
KEY (paper_color)
) ENGINE=InnoDB;
From SQL FOREIGN KEY Constraint
A FOREIGN KEY in one table points to a PRIMARY KEY in another table.
Now from your script, the PRIMARY KEY on table paper consists of columns paper_id, paper_color, but the foreign key referenceing it, only references paper(paper_color)
This techinically allows you to have 2 entries with
paper_id paper_color
1 blue
2 blue
which would satisfy the primary key constraint of table paper, but not the foreign key constraint on table brick
Changing the primary key on table paper to only paper_color would work though.
create table paper (
paper_id int(20) not null,
description VARCHAR(40)not null,
paper_color VARCHAR(40) NOT NULL,
primary key ( paper_color)
)engine=InnoDB;
create table brick(
brick_id int(20) not null,
description varchar(40) not null,
brick_color varchar (40) not null,
primary key (brick_id),
foreign key (brick_color) references paper(paper_color)
)engine=InnoDB
SQL Fiddle DEMO