Error Code: 1215 in mysql cannot add foreign key constraint - mysql

I am getting an issue and I feel like I fixed everything. MySQL workbench is still giving me this error. If you can please explain what is wrong I would be greatly appreciate it. I did check for key constraints in the Account table. It is giving the error in the account table.
CREATE TABLE Account(
AcctNum int AUTO_INCREMENT,
MemberID int,
Balance double,
PIN int,
creationDate date,
InitialBalance double,
CreatedByEmployee int,
type VARCHAR(20),
PRIMARY KEY(AcctNum),
FOREIGN KEY(MemberID) REFERENCES Member(MemNum),
FOREIGN KEY(CreatedByEmployee) REFERENCES Employee(EmpId)
);
CREATE TABLE Member(
MemNum int AUTO_INCREMENT,
DOB date,
CreditScore int,
AcctOpened date,
SSN VARCHAR(11),
Address VARCHAR(255),
PRIMARY KEY(MemNum)
);
CREATE TABLE Employee(
EmpId int AUTO_INCREMENT,
DOB date,
SSN VARCHAR(11),
HireDate date,
Salary double,
EmpLevel VARCHAR(50),
PRIMARY KEY(EmpId)
);

You need to create the referencing table first before creating the table which is referring other tables with FOREIGN key.
The order of table creation should be as
CREATE TABLE Member(
MemNum int AUTO_INCREMENT,
DOB date,
CreditScore int,
AcctOpened date,
SSN VARCHAR(11),
Address VARCHAR(255),
PRIMARY KEY(MemNum)
);
CREATE TABLE Employee(
EmpId int AUTO_INCREMENT,
DOB date,
SSN VARCHAR(11),
HireDate date,
Salary double,
EmpLevel VARCHAR(50),
PRIMARY KEY(EmpId)
);
CREATE TABLE Account(
AcctNum int AUTO_INCREMENT,
MemberID int,
Balance double,
PIN int,
creationDate date,
InitialBalance double,
CreatedByEmployee int,
type VARCHAR(20),
PRIMARY KEY(AcctNum),
FOREIGN KEY(MemberID) REFERENCES Member(MemNum),
FOREIGN KEY(CreatedByEmployee) REFERENCES Employee(EmpId)
);

You are creating the Foreign key for Member before creating the table so it does not exist yet. Change the order you are creating the tables.
CREATE TABLE Member(
MemNum int AUTO_INCREMENT,
DOB date,
CreditScore int,
AcctOpened date,
SSN VARCHAR(11),
Address VARCHAR(255),
PRIMARY KEY(MemNum)
);
CREATE TABLE Employee(
EmpId int AUTO_INCREMENT,
DOB date,
SSN VARCHAR(11),
HireDate date,
Salary double,
EmpLevel VARCHAR(50),
PRIMARY KEY(EmpId)
);
CREATE TABLE Account(
AcctNum int AUTO_INCREMENT,
MemberID int,
Balance double,
PIN int,
creationDate date,
InitialBalance double,
CreatedByEmployee int,
type VARCHAR(20),
PRIMARY KEY(AcctNum),
FOREIGN KEY(MemberID) REFERENCES Member(MemNum),
FOREIGN KEY(CreatedByEmployee) REFERENCES Employee(EmpId)
);

Ofcourse the order of table creation is important here.
Create the Member and Employee tables first, followed by the Account. It should work fine.

you have wrong order of creating tables
try this
1- Create member table first
2- employer table second
3- account table in last
http://www.sqlfiddle.com/#!2/47d58

Related

ERROR 1215 (HY000): Cannot add foreign key constraint error

This is what I have written:
create table employee (
emp_id int,
emp_first_name varchar(20),
emp_last_name varchar(20),
dept_id int,
email varchar(255),
primary key(emp_id, dept_id)
);
create table department(
dept_id int primary key,
dept_name varchar(255),
gm_no int,
foreign key(dept_id) references employee(dept_id)
);
but when I try to create the department table, it gives me the error(ERROR 1215 (HY000): Cannot add foreign key constraint)
all help is appreciated. thank you.
You have the logic backwards. The dept_id is defined in the department table as the primary key. The foreign key constraint belongs in the tables that reference the department:
create table department(
dept_id int primary key,
dept_name varchar(255),
gm_no int
);
create table employee (
emp_id int,
emp_first_name varchar(20),
emp_last_name varchar(20),
dept_id int,
email varchar(255),
primary key(emp_id, dept_id)
foreign key (dept_id) references department (dept_id)
);
Note that this data structure seems suspicious. I would expect a company called employee to have a unique id for empid. Period.
Employees are obvious in departments, but that could change over time. You would then want another table, say employeeDepartment that captured the changing relationship over time.
Your data model, for instance, would get confusing if an employee starts in department A, switches to B, and then returns to A.
The dept_id in the employee table is not key of any type. Make the dept_in column a KEY, UNIQUE KEY, or PRIMARY KEY on the employee. In your situation, just making it UNIQUE KEY is enough.
As #Sharofiddin said:
create table employee (
emp_id int,
emp_first_name varchar(20),
emp_last_name varchar(20),
dept_id int,
email varchar(255),
primary key(emp_id),
UNIQUE KEY (dept_id) /* add this line and run the query again */
);
create table department(
dept_id int primary key,
dept_name varchar(255),
gm_no int,
foreign key(dept_id) references employee(dept_id)
);
Thank you.

How to Do a Proper CONSTRAINT in MariaDB 10.1.37 / Ver 15.1?

I am using MariaDB, and I am experiencing trouble with introducing a CONSTRAINT.
My version of MariaDB:
Ver 15.1 Distrib 10.1.37-MariaDB
My error message:
ERROR 1005 (HY000): Can't create table `schedulingGUI`.`#sql-1043_1a` (errno: 150 "Foreign key constraint is incorrectly formed")
My table entry for city:
CREATE TABLE city
(
cityId INT unsigned NOT NULL AUTO_INCREMENT,
city VARCHAR(50),
countryId INT unsigned,
customerName VARCHAR(50),
address VARCHAR(50),
postalCode VARCHAR(50),
phone VARCHAR(50),
createDate VARCHAR(50),
createdBy VARCHAR(50),
lastUpdateBy VARCHAR(50),
PRIMARY KEY (cityId)
);
My table entry for customer:
CREATE TABLE customer
(
customerId INT unsigned NOT NULL AUTO_INCREMENT,
customerName VARCHAR(50),
addressId INT unsigned,
active INT unsigned,
address VARCHAR(50),
city VARCHAR(50),
postalCode VARCHAR(50),
phone VARCHAR(50),
createDate VARCHAR(50),
createdBy VARCHAR(50),
lastUpdateBy VARCHAR(50),
PRIMARY KEY (customerId)
);
My CONSTRAINT entry:
ALTER TABLE city
ADD CONSTRAINT customerNameChange01
FOREIGN KEY (customerName)
REFERENCES customer (customerName)
ON UPDATE CASCADE
ON DELETE CASCADE;
I recently stumbled across SHOW ENGINE INNODB STATUS. It states the following:
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.
Thank you for your insight.
EDIT: Content added. Corrected the error message.
The following worked:
CREATE INDEX CustomerName ON customer (customerName);
SHOW ENGINE INNODB STATUS; helped a lot.

error 1005 cant create table user.EMPLOYEE and user.STORE (errno 150)

I am new to SQL and I did everything on my understanding but i can't create the table. says error 1005 can't create table user.EMPLOYEE and user.STORE (errno 150) help
DROP TABLE IF EXISTS EMPLOYEE, STORE, REGION;
CREATE TABLE REGION (
REGION_CODE int NOT NULL AUTO_INCREMENT,
REGION_DESCRIPT varchar(20),
PRIMARY KEY (REGION_CODE)
)Engine=InnoDB;
CREATE TABLE EMPLOYEE (
EMP_CODE int NOT NULL AUTO_INCREMENT,
EMP_TITLE varchar(4),
EMP_LNAME varchar(15),
EMP_FNAME varchar(15),
EMP_INITIAL varchar(1),
EMP_DOB date,
STR_CODE int NOT NULL ,
PRIMARY KEY (EMP_CODE,STR_CODE),
FOREIGN key (STR_CODE) REFERENCES STORE(STORE_CODE)
) Engine=InnoDB;
CREATE TABLE STORE (
STORE_CODE int NOT NULL AUTO_INCREMENT,
STORE_NAME varchar(20),
STORE_YRD_SALES numeric,
REGION_CODE int,
EMP_CODE int NOT NULL,
PRIMARY KEY (STORE_CODE),
FOREIGN KEY (REGION_CODE) REFERENCES REGION(REGION_CODE),
FOREIGN KEY (EMP_CODE) REFERENCES EMPLOYEE(EMP_CODE)
) Engine=InnoDB;
Error 150 is an invalid key constraint which, if that's the order you're creating tables in, is probably caused by the fact you can't add a constraint in employee for the currently-not-existing store.
Not being able to create store is simply a side effect of that issue since employee is not created. Once you fix the problem preventing that, the foreign key restraints in store should be okay.
The easiest solution is to probably create employee without the constraint, then add it in later once store exists. This would be something like (note the missing constraint in the EMPLOYEE table creation):
CREATE TABLE EMPLOYEE (
EMP_CODE int NOT NULL AUTO_INCREMENT,
EMP_TITLE varchar(4),
EMP_LNAME varchar(15),
EMP_FNAME varchar(15),
EMP_INITIAL varchar(1),
EMP_DOB date,
STR_CODE int NOT NULL,
PRIMARY KEY (EMP_CODE,STR_CODE)
);
CREATE TABLE STORE ( <<no change here>> );
ALTER TABLE EMPLOYEE ADD CONSTRAINT EMP2STORE
FOREIGN KEY (STR_CODE) REFERENCES STORE(STORE_CODE);

Foreign Key relationships are not making sense, is there a better way?

I'm having an issue with trying to understand how my tables should relate in my database. I am a beginner and have tried to research on my own. The tables are below
CREATE TABLE PIZZA
(
pizza_id INT AUTO_INCREMENT PRIMARY KEY,
pizza_name VARCHAR (255),
pizza_desc VARCHAR (255),
pizza_price DOUBLE
);
CREATE TABLE CUSTOMER
(
cust_id INT AUTO_INCREMENT PRIMARY KEY,
cust_first_name VARCHAR (255),
cust_last_name VARCHAR (255),
cust_street VARCHAR (255),
cust_apt VARCHAR (255),
cust_city VARCHAR (255),
cust_state CHAR(2),
cust_zip CHAR(5),
cust_home_phone CHAR(10),
cust_mobile_phone CHAR(10),
cust_other_phone CHAR(10)
);
CREATE TABLE PIZZA_ORDER
(
pizza_order_id INT AUTO_INCREMENT PRIMARY KEY,
pizza_id INT,
cust_id INT,
order_date TIMESTAMP,
order_quantity INT,
order_notes VARCHAR (255),
FOREIGN KEY (pizza_id) REFERENCES PIZZA(pizza_id),
FOREIGN KEY (cust_id) REFERENCES CUSTOMER(cust_id)
);
My question is, how would this work if a record in the PIZZA_ORDER table had let's say two different pizza, meaning two different pizza_ids? I was thinking of just making the primary key of PIZZA_ORDER not unique and having x number of records for each actual order. But I'm not sure how that would work. Thanks again for any light you guys can shed on this.
A Sales Order hasMany Sales Order Line Items
create table orders (
id int primary key,
...
);
create table order_items (
order_id int references orders(id),
line int,
pizza_id int references pizza(id),
...
primary key (order_id, line)
);
Please see https://dba.stackexchange.com/questions/12991/ready-to-use-database-models-example/23831#23831 to save time :)
You should rather have a relation between pizza_order to pizza table and between Customer to pizza_order table. It's like saying, every pizza is related to one/more pizza order; whereas every pizza order is related to one/more customer.
CREATE TABLE PIZZA_ORDER
(
pizza_order_id INT AUTO_INCREMENT PRIMARY KEY,
order_date TIMESTAMP,
order_quantity INT,
order_notes VARCHAR (255),
cust_id int,
FOREIGN KEY (cust_id) REFERENCES CUSTOMER(cust_id)
);
CREATE TABLE PIZZA
(
pizza_id INT AUTO_INCREMENT PRIMARY KEY,
pizza_name VARCHAR (255),
pizza_desc VARCHAR (255),
pizza_price DOUBLE,
pizza_order_id INT,
FOREIGN KEY (pizza_order_id) REFERENCES PIZZA_Order(pizza_order_id)
);

Creating a table, SQL. Basic stuff

So I'm having a small problem with creating a table. The problem is in my attempt to create a foreign key to another table. I'm currently using MYSQL2008 Management R2 express, so no designer. Heres my two tables
use teckDB;
CREATE TABLE inventory
(
primId int NOT NULL PRIMARY KEY,
prodName VarChar(255),
quantity int,
prodCost MONEY,
prodDesc VARCHAR(255)
);
CREATE TABLE orderTB
(
primId INT NOT NULL PRIMARY KEY,
orderId INT NOT NULL,
created date,
prodId INT,
);
Those two tables ran without a problem. When create the thrid one however causes this error message.
Msg 1769, Level 16, State 1, Line 3 Foreign key 'orderTB' references
invalid column 'orderTB' in referencing table 'CustomerTB'. Msg 1750,
Level 16, State 0, Line 3 Could not create constraint. See previous
errors.
On the thrid table of....
CREATE TABLE CustomerTB
(
primId INT NOT NULL PRIMARY KEY,
orderId INT, FOREIGN KEY (orderTB) REFERENCES orderTB(orderId),
fName VARCHAR(50),
lName VARCHAR(50),
addLN1 VARCHAR(255),
addLN2 VARCHAR(255),
addCity VARCHAR(255),
addPro VARCHAR(255),
addPST VARCHAR(7)
);
try this
FOREIGN KEY (iparent_id) REFERENCES innodb_parent (iparent_id)
I think this should help to solve your query
http://blog.sqlauthority.com/2008/09/08/sql-server-%E2%80%93-2008-creating-primary-key-foreign-key-and-default-constraint/
You have an extra comma after "orderId INT", and you have got the foreign key syntax wrong.
This should work:
CREATE TABLE CustomerTB
(
primId INT NOT NULL PRIMARY KEY,
orderId INT REFERENCES orderTB(orderId),
fName VARCHAR(50),
lName VARCHAR(50),
addLN1 VARCHAR(255),
addLN2 VARCHAR(255),
addCity VARCHAR(255),
addPro VARCHAR(255),
addPST VARCHAR(7)
);
tested on SQLFiddle here