MySQL - error 1215, cannot add foreign key constraint - mysql

I know there are numerous questions regarding this error on here but I've searched through many and none seem to explain it in my case!
I've created a table using the following code:
CREATE TABLE Venue (
venueID VARCHAR(20),
venueEmail VARCHAR(30) NOT NULL,
address VARCHAR(100),
phoneNo VARCHAR(20),
managerNo VARCHAR(20),
capacity INT(4),
PRIMARY KEY (venueEmail)
)ENGINE=InnoDB;
And am trying to create a table with a foreign key that refers to the first table using this code:
CREATE TABLE Concert (
referenceNo VARCHAR(6),
venueEmail VARCHAR(30),
eventDate VARCHAR(10),
startTime VARCHAR(5),
ticketsSold INT(4),
PRIMARY KEY (referenceNo),
FOREIGN KEY (venueEmail) REFERENCES Venue ON UPDATE CASCADE ON DELETE CASCADE
)ENGINE=InnoDB;
But it's giving me the 1215 error message!

Syntax wise this isn't correct.
The issue's resolved here:
CREATE TABLE Venue (
venueID VARCHAR(20),
venueEmail VARCHAR(30) NOT NULL,
address VARCHAR(100),
phoneNo VARCHAR(20),
managerNo VARCHAR(20),
capacity INT(4),
PRIMARY KEY (venueEmail)
)ENGINE=InnoDB;
CREATE TABLE Concert (
referenceNo VARCaHAR(6),
venueEmail VARCHAR(30),
eventDate VARCHAR(10),
startTime VARCHAR(5),
ticketsSold INT(4),
PRIMARY KEY (referenceNo),
FOREIGN KEY (venueEmail) REFERENCES Venue(`venueEmail`) ON UPDATE CASCADE ON DELETE CASCADE
)ENGINE=InnoDB;
Note:
The column being referenced should be stated like table_name(column_name).
You missed the column_name part.
REFERENCE
More:
#Bill Karwin added the following useful info in the comment section:
FWIW this is a MySQL idiosyncrasy. In standard SQL, if you omit the
referenced column name, it defaults to the same name as the foreign
key column. But InnoDB doesn't support this shortcut syntax—you must
specify the column in both cases.

Related

Datatype of Primary key made of two attributes in a table used as a foreign key of a different table

I am creating 3 tables in my railway database.One table(TrainTravel) uses two fields (TrainNo) and (TravelDate) as Primary key.
Another table Booking uses (TrainTravelID) as foreign key which takes the primary key of TrainTravel Table.
There should be a datatype which should be defined for (TrainTravelID) in Booking table.
railway_create.sql
use railway;
create table Booking(
PassengerID int(4),
TrainTravelID
);
create table TrainTravel(
TrainNo int(3),
TravelDate date,
TrainName varchar(20),
BoardingStation varchar(20),
Destination varchar(20),
Ac1Seats int(3),
Ac3Seats int(3),
SlSeats int(3),
SeSeats int(3),
constraint JourneyID PRIMARY KEY (TrainNo,TravelDate)
);
create table Person(
Name varchar(20),
LoginID int(4),
Password varchar(20),
Address varchar(50),
Phno int(10),
constraint PRIMARY KEY (LoginID)
);
railway_alter.sql
use railway;
alter table Booking
add constraint fk_TrainTravelID foreign key as (TrainTravelID) references Train(JourneyID),
add constraint fk_PassengerID foreign key as (PassengerID) references Person(LoginID);
I want to know the datatype of combined primary key of TrainTravel so that it can be used as datatype of TrainTravelID attribute in Booking table.
Without placing any datatype it is giving error,
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(int(3),date)
)' at line 3
TrainTravelID has no data type in Booking.
You need a couple also in Booking.
create table Booking(
PassengerID int(4),
TrainNo int(3),
TravelDate date
);
create table TrainTravel(
TrainNo int(3),
TravelDate date,
TrainName varchar(20),
BoardingStation varchar(20),
Destination varchar(20),
Ac1Seats int(3),
Ac3Seats int(3),
SlSeats int(3),
SeSeats int(3),
constraint JourneyID PRIMARY KEY (TrainNo,TravelDate)
);
create table Person(
Name varchar(20),
LoginID int(4),
Password varchar(20),
Address varchar(50),
Phno int(10),
constraint PRIMARY KEY (LoginID)
);
alter table Booking
add constraint fk_TrainTravelID foreign key(TrainNo,TravelDate) references TrainTravel(TrainNo,TravelDate),
add constraint fk_PassengerID foreign key(PassengerID) references Person(LoginID);

Trying to create a joint table in MySQL but foreign key does not work

This is what I have tried:
create table books(bcode int(5) primary key, bname varchar(45));
and
create table customers(cid int(4), cname varchar(20), cadd varchar(40), bcode,
varchar(45), foreign key(bcode) references books(bcode));
After executing the second statement, the following error shows up:
ERROR 1215 (HY000): Cannot add foreign key constraint
I'm having trouble coming up with a solution. Any help is appreciated.
In the first table books you use bcode as integer
But in the second table you use bcode as varchar,
So, right one is
create table customers(cid int(4), cname varchar(20), cadd varchar(40), bcode
int(5), foreign key(bcode) references books(bcode));

Foreign Key Constraint Error - MySQL

I am trying to create a database containing information from a game for an assignment but am having issues when creating the tables with assigning the primary and foreign keys. Any help would be amazing.
The error code I am getting is: #1215 - Cannot add foreign key constraint on table Boss. It creates the first table fine it just stops working and throws the error at the foreign key when creating table boss.
Within the item table the field Boss needs to be able have the same data entered for multiple different items.
CREATE TABLE item ( ID SERIAL, Name VARCHAR(35), Boss VARCHAR(25), Type VARCHAR(20), Slot VARCHAR(20), PRIMARY KEY (Name,Boss) );
CREATE TABLE boss ( ID SERIAL, Boss VARCHAR(25), Type VARCHAR(20), Location VARCHAR(20), Difficulty INT, PRIMARY KEY (ID, Location), FOREIGN KEY (Boss) REFERENCES item(Boss) );
CREATE TABLE dungeon ( ID SERIAL, Name VARCHAR(25), Location VARCHAR(20), Rating INT, PRIMARY KEY (Name), FOREIGN KEY (Location) REFERENCES boss(Location) );
I can see many things wrong with your db creation script, but I will only stick to the ones that immediately affect getting it to work in the first place:
You should always refer to another table through its primary key and nothing else.
Your references are put in the wrong tables. If you want to refer to a "boss" from "item" then you should do just that and not refer to "item" from "boss".
But the most important thing is that references should be of the same type as the primary keys they refer to.
A composite key is a bad idea when you don't really need one.
So, a working script would be:
CREATE TABLE dungeon ( ID BIGINT(20), Name VARCHAR(25), Location VARCHAR(20), Rating INT, PRIMARY KEY (ID) );
CREATE TABLE boss ( ID BIGINT(20), Type VARCHAR(20), LocationId BIGINT(20), Difficulty INT, PRIMARY KEY (ID), FOREIGN KEY (LocationId) REFERENCES dungeon (ID) );
CREATE TABLE item ( ID BIGINT(20), Name VARCHAR(35), BossId BIGINT(20), Type VARCHAR(20), Slot VARCHAR(20), PRIMARY KEY (ID), FOREIGN KEY (BossId) REFERENCES boss (ID) );
You can adjust it to your needs, but before doing that, I would suggest reading a good book on database design or -at least- a tutorial on basic relational databases principles.

Unable to alter table with foreign key

My two empty tables:
CREATE TABLE person (
person_id SMALLINT UNSIGNED,
fname VARCHAR(20),
lname VARCHAR(20),
gender ENUM('m', 'f'),
birth_date DATE,
street VARCHAR(30),
city VARCHAR(20),
state VARCHAR(20),
country VARCHAR(20),
postal_code VARCHAR(20),
CONSTRAINT pk_person PRIMARY KEY (person_id)
);
create TABLE favorite_food (
person_id SMALLINT UNSIGNED,
food VARCHAR(20),
CONSTRAINT pk_favorite_food PRIMARY KEY (person_id, food),
CONSTRAINT fk_fav_food_person_id FOREIGN KEY (person_id) REFERENCES person (person_id)
);
Needed modification:
ALTER TABLE person MODIFY person_id SMALLINT UNSIGNED AUTO_INCREMENT;
Result:
ERROR 1833 (HY000): Cannot change column 'person_id': used in a
foreign key constraint 'fk_fav_food_person_id' of table
'tom.favorite_food'
Why is this and is there a way around this without dropping the tables and redefining them?
This is probably because there already is data in person.person_id in any rows (NOT NULL). You can circumvent this by disabling foreign key checks
I believe the best way to handle this is to drop the foreign key reference from favorite_food, alter the column in person and then recreate the foreign key reference. That will properly recreate the index on which the key depends.

MySQL #1005 can't create table, but don't says why, errno:150

I'm making a database, with several tables, and so far I could make the tables, and update it with some demo data, but when a tried to make a new table for connecting two of my tables I just get this can't create table error whatever I did. Tried to rename the entities to an entirely different name maybe that's the problem but it wasn't.
CREATE DATABASE IF NOT EXISTS ETR;
CREATE TABLE Hallgato (
OktAzonosito INT(6) PRIMARY KEY,
EHAazonosito VARCHAR(11),
TeljesNev VARCHAR(50),
Szemelyazonosito INT(6),
AnyaNyelv VARCHAR(20),
VegzettsegSzint VARCHAR(25),
AnyjaNeve VARCHAR(35),
SzuletesiHely VARCHAR(30),
SzuletesiEv DATE,
Allampolgarsag VARCHAR(30),
Neme VARCHAR(5),
Adoazonosito INT(6),
TAJszam INT(6),
BankszamlaSzam INT(9)
) ENGINE = InnoDB;
CREATE TABLE OktAdat (
OktAzonosito INT(6),
NyelvVizsgaNyelve VARCHAR(15),
NyVegzesDatuma DATE,
NyIntezmeny VARCHAR(35),
EgyebVegzetteseg VARCHAR(15),
EgyVegzesDatuma DATE,
ID INT(5) PRIMARY KEY NOT NULL auto_increment,
FOREIGN KEY (OktAzonosito) REFERENCES Hallgato(OktAzonosito) ON DELETE CASCADE
) ENGINE = InnoDB;
CREATE TABLE Oktato (
TEHAazonosito VARCHAR(11) PRIMARY KEY,
Nev VARCHAR(50),
SzuletesiEv DATE,
Szakterulet VARCHAR(25),
Telefonszam INT(9),
Email VARCHAR(50)
) ENGINE = InnoDB;
CREATE TABLE Kurzus (
KurzusKod VARCHAR(8) PRIMARY KEY,
KurzusNev VARCHAR(30),
Idotartam INT(3),
EloadasHelye VARCHAR(25),
Tipus CHAR(3),
Vizsgatipus VARCHAR(7),
KreditErtek INT(2),
OktatoKod VARCHAR(11)
) ENGINE = InnoDB;
CREATE TABLE Terem (
Sorszam INT(3) PRIMARY KEY NOT NULL,
Epuletszam INT(1),
Kapacitas INT(3),
IRszam INT(4),
Utca CHAR(25),
Hazszam INT(2)
) ENGINE = InnoDB;
CREATE TABLE DiakKurz (
kd_id INT (5) PRIMARY KEY NOT NULL auto_increment,
DKKod VARCHAR(8),
EHA VARCHAR(11),
FOREIGN KEY (EHA) REFERENCES Hallgato(EHAazonosito) ON DELETE CASCADE,
FOREIGN KEY (DKKod) REFERENCES Kurzus(KurzusKod) ON DELETE CASCADE
) ENGINE = InnoDB;
The problem is with creating the DiakKurz table.
You'll have to set an INDEX for column EHAazonosito in table Hallgato
CREATE TABLE Hallgato (
OktAzonosito INT(6) PRIMARY KEY,
EHAazonosito VARCHAR(11), INDEX (EHAazonosito),
TeljesNev VARCHAR(50),
Szemelyazonosito INT(6),
AnyaNyelv VARCHAR(20),
VegzettsegSzint VARCHAR(25),
AnyjaNeve VARCHAR(35),
SzuletesiHely VARCHAR(30),
SzuletesiEv DATE,
Allampolgarsag VARCHAR(30),
Neme VARCHAR(5),
Adoazonosito INT(6),
TAJszam INT(6),
BankszamlaSzam INT(9)
) ENGINE = InnoDB;
This
FOREIGN KEY (EHA) REFERENCES Hallgato(EHAazonosito) ON DELETE CASCADE,
doesn't work because EHAazonosito is not the primary key of the Hallgato table. A foreign key can only reference a primary (or unique) key.
Btw: are you awary that the 6 in int(6) is not about limiting the values in the column?
It doesn't do anything. int(6) is the same as int. The 6 is only there to give client applications a hint(!) with how many digits the column should be displayed. It does not enforce anything at all.
Have you tried looking up the error?
If MySQL reports an error number 1005 from a CREATE TABLE statement,
and the error message refers to error 150, table creation failed
because a foreign key constraint was not correctly formed. Similarly,
if an ALTER TABLE fails and it refers to error 150, that means a
foreign key definition would be incorrectly formed for the altered
table. To display a detailed explanation of the most recent InnoDB
foreign key error in the server, issue SHOW ENGINE INNODB STATUS.
http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html
it happened also to me after a dump of the whole schema, what helped was to wrap whole dump within disabled foreign key checks
SET foreign_key_checks=0;
...dump
SET foreign_key_checks=1;