Cannot add foreign key restraint error in MySQL? - mysql

I keep getting the same error in MySQL and i'm not sure what I missing here.
I am very new to working with MySQL, so I am not sure if I need to add a constraint maybe? If I do not need a constraint, is there another way to go about defining the relationships? Below is my syntax:
DROP TABLE IF EXISTS `art`;
CREATE TABLE `art` (
`art_id` INT NOT NULL,
`art_name` VARCHAR(45) NULL,
`artist_id` INT(11) NULL,
`location_id` INT(11) NULL,
`employee_id` INT(11) NULL,
`art_received` DATE NULL,
primary key (`art_id`),
FOREIGN KEY (`artist_id`) REFERENCES artist(`artist_id`),
FOREIGN KEY (`location_id`) REFERENCES location(`location_id`),
FOREIGN KEY (`employee_id`) REFERENCES employee(`employee_id`)
);
DROP TABLE IF EXISTS `employee`;
CREATE TABLE `employee` (
`employee_id` int(11),
`employee_userid` varchar(45),
`employee_fname` varchar(45),
`employee_lname` varchar(45),
`employee_phone` varchar (10),
primary key (`employee_id`)
);
DROP TABLE IF EXISTS `artist`;
CREATE TABLE `artist` (
`artist_id` int(11),
`artist_first` varchar(45),
`artist_last` varchar(45),
`artwork_title` varchar(45),
primary key (`artist_id`)
);
DROP TABLE IF EXISTS `location`;
CREATE TABLE `location` (
`location_id` int(11),
`location_name` varchar(45),
`start_date` date,
`end_date` date,
primary key (`location_id`)
);

simply switch the order of which table gets created first. when you created
table art the other three table still have not be created so it doesn't know what artist(artist_id),location(location_id),employee(employee_id)
are.
DROP TABLE IF EXISTS `employee`;
CREATE TABLE `employee` (
`employee_id` int(11),
`employee_userid` varchar(45),
`employee_fname` varchar(45),
`employee_lname` varchar(45),
`employee_phone` varchar (10),
primary key (`employee_id`)
);
DROP TABLE IF EXISTS artist;
CREATE TABLE `artist` (
`artist_id` int(11),
`artist_first` varchar(45),
`artist_last` varchar(45),
`artwork_title` varchar(45),
primary key (`artist_id`)
);
DROP TABLE IF EXISTS `location`;
CREATE TABLE `location` (
`location_id` int(11),
`location_name` varchar(45),
`start_date` date,
`end_date` date,
primary key (`location_id`)
);
DROP TABLE IF EXISTS `art`;
CREATE TABLE `art` (
`art_id` INT NOT NULL,
`art_name` VARCHAR(45) NULL,
`artist_id` int(11) NULL,
`location_id` int(11) NULL,
`employee_id` int(11) NULL,
`art_received` DATE NULL,
primary key (`art_id`),
FOREIGN KEY (`artist_id`) REFERENCES artist(`artist_id`),
FOREIGN KEY (`location_id`) REFERENCES location(`location_id`),
FOREIGN KEY (`employee_id`) REFERENCES employee(`employee_id`)
);
And welcome to StackOverflow. if you find this answer or any other answer helpful please mark it as the solution. That way would help the community and if fellow programmers run into the same problem as you did in the future they can find the solution easily.

Related

I am trying to create a table in MySQL but I get the following error:

"Error Code: 1822. Failed to add the foreign key constraint. Missing index for constraint 'users_ibfk_1' in the referenced table 'users'"
Here's what I have so far:
DROP TABLE IF EXISTS `books`;
CREATE TABLE `books`(
`title` VARCHAR(50) NOT NULL,
`year` INT,
`edition` VARCHAR(10),
`authorLast` VARCHAR(10),
`authorFirst` VARCHAR(10),
`major` VARCHAR(4),
`courseNo` INT,
`profLast` VARCHAR(10),
`profFirst` VARCHAR(10),
`quality` VARCHAR(10) NOT NULL,
`price` FLOAT NOT NULL,
`user` VARCHAR(10) NOT NULL UNIQUE,
`ISBN` BIGINT NOT NULL,
PRIMARY KEY (`ISBN`)
);
-- Users Table
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users`(
`nameFirst` VARCHAR(10) NOT NULL,
`nameLast` VARCHAR(10),
`user` VARCHAR(10) NOT NULL UNIQUE,
`email` VARCHAR(20) NOT NULL,
`phoneNo` INT,
`major` VARCHAR(10),
`major2` VARCHAR(10),
PRIMARY KEY (`email`),
FOREIGN KEY (`user`) REFERENCES `users` (`user`) ON DELETE CASCADE ON UPDATE CASCADE
);
I've tried making the attributes unique because I read somewhere that that could be the problem but that doesn't seem to be my issue. I'm coming back to MySQL for the first time in a while so this can be a really simple error I'm just not seeing but I would appreciate the help! Thanks.
Your foreign key in the users table is referring same user column in same table

MYSQL Err #1072 doesn't exist in table when specifying FK

I am new to mysql, so sorry if this is a trivial problem. Problem is when I create the second table I get the error:
key iplogger_redirect_key doesn't exist.
Here's my code:
DROP DATABASE iploggerdb;
CREATE DATABASE iploggerdb;
USE iploggerdb;
CREATE TABLE iplogger_info_table(
iplogger_redirect_key CHAR(8) PRIMARY KEY,
access_key CHAR(8) NOT NULL,
creation_timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
creator_ip VARCHAR(45),
original_url VARCHAR(2000)
);
CREATE TABLE logs_table(
id INT(11) AUTO_INCREMENT,
iplogger_redirect_key FOREIGN KEY (iplogger_redirect_key) REFERENCES iplogger_info_table(iplogger_redirect_key),
logged_ip VARCHAR(45),
logged_dns_server VARCHAR(45),
logged_ip_country_city VARCHAR(200),
logged_hostname VARCHAR(200),
logged_user_agent VARCHAR(150),
logged_referrer VARCHAR(2000),
logged_ip_timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
You need to correct FOREIGN KEY part:
CREATE TABLE logs_table(
id INT(11) AUTO_INCREMENT PRIMARY KEY,
iplogger_redirect_key CHAR(8),
CONSTRAINT fk_name FOREIGN KEY (iplogger_redirect_key)
REFERENCES iplogger_info_table(iplogger_redirect_key),
...
)
DBFiddle Demo

Adding constraints to tables in MySQL

I'm creating a db for a theater. It currently has only two tables: shows and movies.
Each movie has (besides the auto increment id int not null), a unique string id (also not null), which I would like to use as a foreign key inside of the shows table. Its giving me:
Error Code: 1215. Cannot add foreign key constraint
Here is my query:
SET FOREIGN_KEY_CHECKS=0;
DROP TABLE movies CASCADE;
DROP TABLE shows CASCADE;
SET FOREIGN_KEY_CHECKS=1;
CREATE TABLE movies (
`movies_id` INT auto_increment,
`movie_id` VARCHAR(18) NOT NULL,
`title` VARCHAR(100),
`original_title` VARCHAR(100),
`punchline` VARCHAR(250),
`genre` VARCHAR(60),
`year` INT,
`duration` INT,
`url` VARCHAR(150),
`poster` VARCHAR(150),
`director` VARCHAR(45),
`producer` VARCHAR(45),
`writer` VARCHAR(100),
`cast` VARCHAR(500),
`distributor` VARCHAR(45),
`language` VARCHAR(45),
`country` VARCHAR(100),
`localization` VARCHAR(45),
`plot_outline` VARCHAR(800),
`sum_of_scores` DOUBLE,
`num_of_scores` DOUBLE,
PRIMARY KEY (`movies_id`));
CREATE TABLE shows (
`shows_id` INT auto_increment,
`show_id` VARCHAR(18),
`date` DATE,
`time` DATETIME,
`city` VARCHAR(45),
`center` VARCHAR(45),
`theater` VARCHAR(45),
`movies_movie_id` VARCHAR(18),
PRIMARY KEY (`shows_id`));
ALTER TABLE shows
ADD CONSTRAINT fk_shows_movies FOREIGN KEY
(`movies_movie_id`) REFERENCES movies(`movie_id`);
Foreign keys must refer to primary key/ unique key in parent table. In your case, you have two columns movies_id and movie_id, and you have defined movies_id as primary key. But, your foreign key is trying to reference movie_id column. You will need to make this column unique in this circumstance to create your foreign key.

MySQL error 1215, what am I doing wrong?

I am trying to create a database that holds staff information such as their names, timesheets, holidays booked etc and also information about the projects the are carrying out and what companies the projects are for. My code is below:
CREATE TABLE IF NOT EXISTS tblcompany (
companyid INT(11) UNSIGNED NOT NULL,
custfirst VARCHAR(50),
custlast VARCHAR(50),
company VARCHAR(50),
custphone VARCHAR(50),
custemail VARCHAR(50),
PRIMARY KEY (companyid),
INDEX (companyid),
CONSTRAINT FOREIGN KEY (companyid)
REFERENCES tblproject (companyid)
) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS tblemployee (
employeeid INT(11) UNSIGNED NOT NULL,
employeefirst VARCHAR(50),
employeelast VARCHAR(50),
employeephone VARCHAR(50),
employeeemail VARCHAR(50),
PRIMARY KEY (employeeid),
INDEX (employeeid),
CONSTRAINT FOREIGN KEY (employeeid)
REFERENCES tbltimesheet (employeeid),
CONSTRAINT FOREIGN KEY (employeeid)
REFERENCES tblholiday (employeeid),
CONSTRAINT FOREIGN KEY (employeeid)
REFERENCES tblannualleave (employeeid)
) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS tblholiday (
holidayid INT(11) UNSIGNED NOT NULL,
employeeid INT(11) UNSIGNED NOT NULL,
holidayfrom DATE,
holidayto DATE,
holidayhalfday BOOLEAN,
holidayreason VARCHAR(50),
INDEX (employeeid),
PRIMARY KEY (holidayid)
) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS tblannualleave (
annualleaveid INT(11) UNSIGNED NOT NULL,
employeeid INT(11) UNSIGNED NOT NULL,
annualleavetaken INT(11),
annualleaveremain INT(11),
anuualleavetotal INT(11),
INDEX (employeeid),
PRIMARY KEY (annualleaveid)
) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS tblproject (
projectid INT(11) UNSIGNED NOT NULL,
projectname VARCHAR(50),
projecttype VARCHAR(50),
companyid INT(11) UNSIGNED NOT NULL,
projectnotes VARCHAR(50),
PRIMARY KEY (projectid),
INDEX (projectid),
CONSTRAINT FOREIGN KEY (projectid)
REFERENCES tbltimesheet (projectid)
) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS tbltimesheet (
timesheetid INT(11) UNSIGNED NOT NULL,
employeeid INT(11) UNSIGNED NOT NULL,
projectid INT(11) UNSIGNED NOT NULL,
timesheetdate DATE,
timesheethours INT(11),
timesheetnotes VARCHAR(50),
INDEX (employeeid),
PRIMARY KEY (timesheetid)
) ENGINE=InnoDB;
I have been looking around and have tried everything, it is probably something so simple. I have changed all the datatypes to similar ones to see if this would solve the problem butno luck. The error code I get is:
Error Code: 1215. Cannot add foreign key constraint
0.063 sec
CREATE TABLE IF NOT EXISTS tblcompany ( companyid INT(11) UNSIGNED
NOT NULL, custfirst VARCHAR(50), custlast VARCHAR(50),
company VARCHAR(50), custphone VARCHAR(50), custemail
VARCHAR(50), PRIMARY KEY (companyid), INDEX (companyid),
CONSTRAINT FOREIGN KEY (companyid) REFERENCES tblproject
(companyid) ) ENGINE=InnoDB
11:15:57 CREATE TABLE IF NOT EXISTS tblcompany ( companyid INT(11)
UNSIGNED NOT NULL, custfirst VARCHAR(50), custlast
VARCHAR(50), company VARCHAR(50), custphone VARCHAR(50),
custemail VARCHAR(50), PRIMARY KEY (companyid), INDEX
(companyid), CONSTRAINT FOREIGN KEY (companyid) REFERENCES
tblproject (companyid) ) ENGINE=InnoDB Error Code: 1215. Cannot add
foreign key constraint 0.063 sec
Thank you for looking..
Create the table tblproject first before you reference it.
Besides the wrong table order,you need either a primary or unique key on referenced columns.
SQL fiddle
I think you will solve your problem creating your tables in the opposite ordersm, otherwise you will have the same issue with tblemployee.
A Foreigh Key needs that the reference table exists already.
You cannot create a foreign key when the table it references does not yet exist. You can always create the foreign key later.
You must first create the tables containing the referenced fields, after you create the table with the foreign key.
You could also create first all the tables, and create all foreign keys in a second step.

Error 1005(105) can't create table... but why?

create table bankdb.customer(
customer_name varchar(45) not null,
social_security int not null,
customer_street varchar(45),
customer_city varchar(45),
primary key(`social_security`)
)engine=InnoDB;
create table bankdb.branch(
branch_name varchar(45) not null,
branch_city varchar(45),
assets int,
primary key (`branch_name`)
)engine=InnoDB;
create table bankdb.account(
branch_name varchar(45),
account_number varchar(45) not null,
balance int,
primary key (`account_number`),
constraint fk_acount_branch
foreign key (`branch_name`)
references bankdb.branch(`branch_name`)
)engine=InnoDB;
create table bankdb.depositor(
customer_name varchar(45) not null,
account_number varchar(45) not null,
primary key (`customer_name`, `account_number`),
constraint fk_depositor_customer
foreign key(`customer_name`)
references bankdb.customer(`customer_name`),
constraint fk_depositor_account
foreign key(`account_number`)
references bankdb.account(`account_number`)
)engine=InnoDB;
That's my sql code... i get the error can't create table for the table bankdb.depositor... Is there anything wrong with my foreign keys? Any clues?
Edit, based on your new script the following appears to be working in SQL Fiddle. I had to add indexes:
create table bankdb.customer(
customer_name varchar(45) not null,
social_security int not null,
customer_street varchar(45),
customer_city varchar(45),
primary key(`social_security`),
INDEX (customer_name)
)engine=InnoDB;
create table bankdb.branch(
branch_name varchar(45) not null,
branch_city varchar(45),
assets int,
primary key (`branch_name`)
)engine=InnoDB;
create table bankdb.account(
branch_name varchar(45),
account_number varchar(45) not null,
balance int,
primary key (`account_number`),
INDEX (account_number),
constraint fk_acount_branch
foreign key (`branch_name`)
references bankdb.branch(`branch_name`)
)engine=InnoDB;
create table bankdb.depositor(
customer_name varchar(45) not null,
account_number varchar(45) not null,
primary key (`customer_name`, `account_number`),
INDEX (customer_name),
INDEX (account_number),
constraint fk_depositor_customer
foreign key(`customer_name`)
references bankdb.customer(`customer_name`),
constraint fk_depositor_account
foreign key(`account_number`)
references bankdb.account(`account_number`)
)engine=InnoDB;
See SQL Fiddle with Demo
If this is your full script your issue is with the create table for account.
You are trying to create a foreign key on the branch table which doesn't appear to exist:
create table bankdb.account(
branch_name varchar(45),
account_number varchar(45) not null,
balance int,
primary key (`account_number`),
constraint fk_acount_branch
foreign key (`branch_name`)
references bankdb.branch(`branch_name`) -- does this exist
)engine=InnoDB;