mysql error 1215(hy000) cannot add foreign key constraint - mysql

I keep getting this error, I used InnoDB for all tables, menuID, and customerID, are primary keys in their respective tables, and the datatypes appear to be the same.
ERROR 1215 (HY000): Cannot add foreign key constraint
Sorry if I am missing something simple, I am new to mySQL.
create table customers(
customerID int not null auto_increment primary key,
LastName varchar(255) not null,
FirstName varchar(255) not null,
email varchar(255) not null,
password varchar(255),
phone varchar(255),
creditCard varchar(255),
address varchar(255),
time timestamp)
Engine=InnoDB;
create table menu(
menuID int not null auto_increment primary key,
typeID int,
itemName varchar(255),
price varchar(255))
Engine=InnoDB;
create table orders(
orderID int not null,
customerID int not null,
menuID int not null,
PRIMARY KEY (orderID, customerID, menuID),
FOREIGN KEY (customerID) REFERENCES customers(customerID) on delete set null on update cascade,
foreign key (menuID) references menu(menuID) on delete set null on update cascade )
Engine=InnoDB;

You can't use ON DELETE SET NULL for a foreign key column that you declared NOT NULL.
See this answer for a long checklist of things to check as possible causes of foreign key errors: MySQL Creating tables with Foreign Keys giving errno: 150

Related

Failed to add the foreign key constraint in MySQL: error 3780

I am getting the error:
Error Code: 3780. Referencing column 'category' and referenced column 'category_id' in foreign key constraint 'product_ibfk_1' are incompatible.
drop table if exists Provider;
drop table if exists Category;
drop table if exists Product;
create table Provider
(
privider_id serial not null primary key,
login_password varchar(20) not null
constraint passrule3 check(login_password sounds like '[A-Za-z0-9]{6,20}'),
fathersname varchar(20) not null,
name_of_contact_face varchar(10) not null,
surname varchar(15),
e_mail varchar(25) unique
constraint emailrule2 check(e_mail sounds like '[A-Za-z0-9]{10,10})\#gmail.com\s?')
);
create table Category
(
title varchar(20),
category_id serial not null primary key
);
create table Product
(
barecode serial not null primary key,
provider_id bigint not null,
manufacturer varchar(25) not null,
category_id bigint not null,
dimensions varchar(10) not null,
amount int not null,
date_of_registration datetime not null,
#constraint 'provider_for_product'
foreign key (provider_id) references Provider (provider_id) on delete restrict on update cascade,
foreign key (category_id) references Category (category_id) on delete restrict on update cascade
);
The datatypes of the two columns referenced in a foreign key constraint need to match
In MySQL, SERIAL is an alias for BIGINT UNSIGNED AUTO_INCREMENT.
To make a foreign key that references this column, it must be BIGINT UNSIGNED, not a signed BIGINT.
You might like to view a checklist of foreign key mistakes I contributed to: https://stackoverflow.com/a/4673775/20860
I also cover foreign key mistakes in more detail in a chapter of my book, SQL Antipatterns Volume 1: Avoiding the Pitfalls of Database Programming.

MySQL is not creating the table from an imported SQL file correctly

I converted a Microsoft SQL creation table syntax into MySQL and let MySQL import the SQL file, I keep getting an error. This is the code:
CREATE TABLE Adminstration (
AdminID INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
ContactID int constraint fk_Admin_Contact foreign key (ContactID) references ContactInfo(ContactID),
EEID int constraint fk_Admin_Employee foreign key (EEID) references Employees(EEID),
LName VARCHAR(30) NOT NULL,
FName VARCHAR(30) NOT NULL,
EContactID int constraint fk_Admin_EContact foreign key (EContactID) references EmergencyContacts(ECID),
Position VARCHAR(50),
DOB DATE
);
However, I keep getting an error saying:
contraitnt" is not valid at this position for this server version, expecting AS, AUTO_INCREMENT, CHECK< COLLATE, COLUMN_FORMAT, COMMENT...
What is wrong with it?
You have made a small error, the constraints are not valid in the column definition that way.
CREATE TABLE Adminstration (
AdminID INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
ContactID int,
constraint fk_Admin_Contact foreign key (ContactID) references ContactInfo(ContactID),
EEID int,
constraint fk_Admin_Employee foreign key (EEID) references Employees(EEID),
LName VARCHAR(30) NOT NULL,
FName VARCHAR(30) NOT NULL,
EContactID int
,constraint fk_Admin_EContact foreign key (EContactID) references EmergencyContacts(ECID),
Position VARCHAR(50),
DOB DATE
);

i am trying to create foreign keys but i got error 1822 .. please see my code below

CREATE TABLE employee(
empid int auto_increment primary key,
empfirstname varchar(200) not null,
emplastname varchar(200) not null,
email varchar(200) not null,
officenumber int not null
);
CREATE TABLE customer(
custid int auto_increment primary key,
firstname varchar(200) not null,
lastname varchar(200) not null,
address varchar(200) not null,
contact varchar(200)
);
CREATE TABLE product(
productid int auto_increment primary key,
productdesc varchar(500) not null,
weight int not null,
unit_cost int not null
);
CREATE TABLE productorder(
productid int,
orderid int,
primary key(productid,orderid),
constraint fk3 foreign key (productid) references product(productid),
constraint fk4 foreign key (orderid) references productorder(orderid)
);
CREATE TABLE salesorder(
salesorderid int auto_increment primary key,
empid int not null,
custid int not null,
orderdate date not null,
shippingmethod varchar (200) not null,
constraint a_fk1 foreign key (empid) references employee(empid),
constraint a_fk2 foreign key (custid) references customer(custid)
);
What is this meant to do?:
constraint fk4 foreign key (orderid) references productorder(orderid)
It's not uncommon for a table to have a foreign key back to its own primary key, such as for records which have a parent/child relationship. But that doesn't seem to be the case here.
More to the point of the error though, this isn't referencing the entire primary key for the target table. That key has two fields:
primary key(productid,orderid)
So the DBMS can't create the foreign key because its structure doesn't match the target primary key.
If you want to create that foreign key, it would need to match. Probably something like this:
constraint fk4 foreign key (productid,orderid) references productorder(productid,orderid)
But it doesn't appear that you need that foreign key at all, because it doesn't seem to make sense in your data model. Instead I suspect orderid might need to be autoincrement and just use the productid foreign key. Something like this:
CREATE TABLE productorder(
orderid int auto_increment primary key,
productid int,
constraint fk3 foreign key (productid) references product(productid)
);
(Note that there could be more changes you'd want to make to your data model. This answer doesn't purport to provide you with a complete production-ready data model, just to correct the error. Your data model is likely to change/evolve as you develop your system.)
Its normal,
The foreign key in table **productorder**
is refereing to the table itself:
constraint fk4 foreign key (orderid) references **productorder**(orderid)
In order to achieve the self-referencing constraint on the table productorder, you need to add another column with the same type and make typical referencing.
For instance :
Create table productorder (
productid int,
orderid int,
orderid_parent int,
primary key(productid,orderid),
constraint fk_self foreign key(orderid) references productorder(orderid_parent)
)

errno 150 mySQL foreign key

This SQL is giving me Errno 150 when i'm trying to create the second table with the foreign key on UserID
Can anyone please advice me what am i doing wrong?
CREATE DATABASE IF NOT EXISTS OTA;
USE OTA;
CREATE TABLE IF NOT EXISTS Users
(
UserID int AUTO_INCREMENT NOT NULL PRIMARY KEY,
UserName varchar(255) NOT NULL,
Email varchar(255) UNIQUE ,
PW varchar(255),
PN varchar(255),
Admin BIT
);
CREATE TABLE IF NOT EXISTS Notes
(
UID int AUTO_INCREMENT NOT NULL PRIMARY KEY,
Note varchar (255) NOT NULL,
c_Date Date NOT NULL,
c_text varchar (255) NOT NULL,
FOREIGN KEY (UID) REFERENCES Persons(UserID)
);
Sorry for being a duplicate question but i can't find my answer between the related ones.
The problem is that you are trying to reference Persons(UserID) when your first table is called Users. Try this for your key:
FOREIGN KEY (UID) REFERENCES Users(UserID)
However, you should have a separate column for the note ID.
Try declaring the primary key after:
CREATE TABLE Orders
(O_Id int NOT NULL,
OrderNo int NOT NULL,
P_Id int,
PRIMARY KEY (O_Id),
FOREIGN KEY (P_Id) REFERENCES Persons(P_Id))
Also, you auto-incremented both UID and UserID. This is fine if they are the same length, but if you try to reference a foreign key value that doesn't exist, you will get an error.

sql cannot add foreign key constraint

i am trying to create a table that uses a foreign key from another table an i keep getting the error:"1215 cannot add foreign key constraint "
i checked and it says 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.
Note that the internal storage type of ENUM and SET changed in
tables created with >= InnoDB-4.1.12, and such columns in old tables
cannot be referenced by such columns in new tables.
See http://dev.mysql.com/doc/refman/5.6/en/innodb-foreign-key-constraints.html
for correct foreign key definition."
below is my sql code:
show engine innodb status;
CREATE TABLE trainee (
traineeid bigint unsigned NOT NULL,
fname VARCHAR(20),
lname VARCHAR(20),
id INT(9),age INT,
PRIMARY KEY (traineeid));
CREATE TABLE trainer(
trainerid bigint unsigned NOT NULL,
fname VARCHAR(20),lname VARCHAR(20),
id INT(9),
PRIMARY KEY (trainerid));
CREATE TABLE club(
clubid bigint unsigned NOT NULL,
clubname VARCHAR(20),
PRIMARY KEY(clubid));
CREATE TABLE team(
teamid bigint unsigned NOT NULL,
teamname VARCHAR(20),
clubid bigint unsigned,
INDEX(clubid),
FOREIGN KEY (clubid) REFERENCES club (clubid)
ON DELETE SET NULL
ON UPDATE CASCADE,
PRIMARY KEY(teamid));
CREATE TABLE competition(
competitionid bigint unsigned NOT NULL,
competitiondate DATE,
competitionname VARCHAR(40),
PRIMARY KEY(competitionid));
CREATE TABLE trainertoteam(
trainerid bigint unsigned not null,
teamid bigint unsigned not null,
PRIMARY KEY(teamid,trainerid),
INDEX(trainerid),
FOREIGN KEY (trainerid) REFERENCES trainer (trainerid)
ON DELETE set null
ON UPDATE CASCADE,
INDEX(teamid),
FOREIGN KEY (teamid) REFERENCES team (teamid)
ON DELETE CASCADE
ON UPDATE CASCADE);
could you help me to find what is the error?
i know the error is when creating trainertoteam table