Cannot add foreign keys constraint - mysql

CREATE TABLE tblTransaction (
strTransCode VARCHAR(50) NOT NULL,
dtmTransDate datetime,
strTransDesc VARCHAR(50) NOT NULL,
dblTransAmt double,
intVoucRefCodeTrans INT,
FOREIGN KEY (intVoucRefCodeTrans) REFERENCES tblVoucher (intVoucRefCode) ON DELETE RESTRICT ON UPDATE CASCADE,
PRIMARY KEY (strTransCode)
)ENGINE=InnoDB;
CREATE TABLE tblVoucher (
intVoucRefCode INT,
strVoucRefDesc VARCHAR(50) NOT NULL,
dtmVoucDate datetime,
PRIMARY KEY (intVoucRefCode)
)ENGINE=InnoDB;
these are my tables I don't know why it displays "Cannot add foreign key constraint" please help

First create tblVoucher table then reference it in tblTransaction table
CREATE TABLE tblVoucher (
intVoucRefCode INT,
strVoucRefDesc VARCHAR(50) NOT NULL,
dtmVoucDate datetime,
PRIMARY KEY (intVoucRefCode)
)ENGINE=InnoDB;
CREATE TABLE tblTransaction (
strTransCode VARCHAR(50) NOT NULL,
dtmTransDate datetime,
strTransDesc VARCHAR(50) NOT NULL,
dblTransAmt double,
intVoucRefCodeTrans INT,
FOREIGN KEY (intVoucRefCodeTrans) REFERENCES tblVoucher (intVoucRefCode) ON DELETE RESTRICT ON UPDATE CASCADE,
PRIMARY KEY (strTransCode)
)ENGINE=InnoDB;
DEMO

Related

Getting error while altering table in MySQL

I wrote a sql file to create a Database and add tables in that database.
Here is the code:
CREATE SCHEMA `employee_details`;
CREATE TABLE `employee_details`.`employee` (
`emp_id` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(45),
`dob` DATE,
`joiningdate` DATE,
`designation_id` INT,
`gender` VARCHAR(45),
`address` VARCHAR(90),
`manager_id` INT,
PRIMARY KEY (`emp_id`)
);
CREATE TABLE `employee_details`.`designation` (
`designation_id` INT NOT NULL AUTO_INCREMENT,
`designation` VARCHAR(45),
`dept_id` INT,
`salary` FLOAT,
PRIMARY KEY (`designation_id`)
);
CREATE TABLE `employee_details`.`department` (
`dept_id` integer NOT NULL AUTO_INCREMENT,
`dept_name` VARCHAR(45),
PRIMARY KEY (`dept_id`)
);
CREATE TABLE `employee_details`.`rating` (
`emp_id` INT,
`emp_rating` INT,
`add_perks` FLOAT,
`experience` INT
);
CREATE TABLE `employee_details`.`project_assign` (
`emp_id` INT,
`project_id` INT
);
CREATE TABLE `employee_details`.`project` (
`project_id` INT NOT NULL AUTO_INCREMENT,
`project_name` VARCHAR(45),
`project_dept` INT,
PRIMARY KEY (`project_id`)
);
ALTER TABLE employee
ADD FOREIGN KEY (emp_id) REFERENCES rating(emp_id);
ALTER TABLE employee
ADD FOREIGN KEY (emp_id) REFERENCES project_assign(emp_id);
ALTER TABLE employee
ADD FOREIGN KEY (emp_id) REFERENCES employee(manager_id);
ALTER TABLE designation
ADD FOREIGN KEY (designation_id) REFERENCES employee(designation_id);
ALTER TABLE designation
ADD FOREIGN KEY (dept_id) REFERENCES department(dept_id);
ALTER TABLE department
ADD FOREIGN KEY (dept_id) REFERENCES project(project_dept);
ALTER TABLE project
ADD FOREIGN KEY (project_id) REFERENCES project_assign(project_id);
When I execute that sql file, I get below error:
15:16:50 ALTER TABLE employee ADD FOREIGN KEY (emp_id) REFERENCES rating(emp_id) Error Code: 1822. Failed to add the foreign key constraint. Missing index for constraint 'employee_ibfk_1' in the referenced table 'rating' 0.000 sec
I checked data types of emp_id in employee and rating. They are same. How can I fix this error?
All your foreign key relationships are backwards. It should be:
ALTER TABLE rating
ADD FOREIGN KEY (emp_id) REFERENCES employee(emp_id);
and similar for all the other foreign keys.

can't add foreign key constraint

CREATE TABLE tblTransaction (
strTransCode VARCHAR(50) NOT NULL,
dtmTransDate datetime,
strOwnCode VARCHAR(50) NOT NULL,
strOwnName VARCHAR(50) NOT NULL,
strTransDesc VARCHAR(50) NOT NULL,
dblTransAmt double,
strAcctCode VARCHAR(50) NOT NULL,
strEntryCode VARCHAR(50) NOT NULL,
FOREIGN KEY (strEntryCode) REFERENCES tblEntry (strEntryCode) ON DELETE RESTRICT ON UPDATE CASCADE,
FOREIGN KEY (strAcctCode) REFERENCES tblAccount (strAcctCode) ON DELETE RESTRICT ON UPDATE CASCADE,
PRIMARY KEY (strTransCode)
)ENGINE=InnoDB;
CREATE TABLE tblVoucher (
intVoucRefCode INT,
strVoucRefDesc VARCHAR(50) NOT NULL,
dtmVoucDate datetime,
strOwnCode VARCHAR(50) NOT NULL,
strOwnVoucCode VARCHAR(50) NOT NULL,
FOREIGN KEY (strOwnVoucCode) REFERENCES tblTransaction(strOwnCode) ON DELETE RESTRICT ON UPDATE CASCADE,
PRIMARY KEY (intVoucRefCode)
)ENGINE=InnoDB;
can't add foreign key constraint help
can't add foreign key constraint help
can't add foreign key constraint help
can't add foreign key constraint help
To create a foreign key for strOwnCode from table tblTransaction you need to define strOwnCode as primary key
CREATE TABLE tblTransaction (
strTransCode VARCHAR(50) NOT NULL,
dtmTransDate datetime,
strOwnCode VARCHAR(50) NOT NULL,
strOwnName VARCHAR(50) NOT NULL,
strTransDesc VARCHAR(50) NOT NULL,
dblTransAmt double,
strAcctCode VARCHAR(50) NOT NULL,
strEntryCode VARCHAR(50) NOT NULL,
PRIMARY KEY (strOwnCode)
)ENGINE=InnoDB;
DEMO

Error Code : 1005 Can't create table 'custom_db2.durableprofile' (errno: 150)

can't create database
--------------------------------------------------------
create table DurableArticle(
durable_code varchar(30) not null,
durable_name varchar(100),
durable_number varchar(20),
durable_brandname varchar(125),
durable_modelordetail varchar(125),
durable_price varchar(20),
durable_entrance varchar(20),
constraint durable_PK primary key (durable_code)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
---------------------------------------------
create table DurableProfile(
profile_year integer not null,
profile_status varchar(100),
profile_note varchar(100),
staff_id integer not null,
owner_id integer not null,
room_id integer not null,
durable_code varchar(30) not null,
constraint profile_PK primary key (profile_year,durable_code),
constraint profile_FK1 foreign key (staff_id) references staff(staff_id),
constraint profile_FK2 foreign key (owner_id) references owner(owner_id),
constraint profile_FK3 foreign key (room_id) references room(room_id),
constraint profile_Fk4 foreign key (durable_code) references durablearticle (durable_code)
)ENGINE=InnoDB;
you reference 3 tables in the second statement, which obviously do not exist (yet).
Remove the foreign keys or create those tables, then it works.
create table DurableProfile(
profile_year integer not null,
profile_status varchar(100),
profile_note varchar(100),
staff_id integer not null,
owner_id integer not null,
room_id integer not null,
durable_code varchar(30) not null,
constraint profile_PK primary key (profile_year,durable_code),
constraint profile_Fk4 foreign key (durable_code) references durablearticle (durable_code)
)ENGINE=InnoDB;

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;