MySql error 1215: Cannot add foreign key constraint - mysql

in my RIM I got the 1215 MySql error.
I know the meaning of the error, that my constraints are wrong. But I can't seem to fix it.
the error is at line 33, the creation of table Poker_event
create table Poker_event
(date_time datetime not null,
min_players int not null,
max_players int not null,
house_number int not null,
postal_code varchar(6) not null,
primary key(date_time),
foreign key(house_number, postal_code) references Location(house_number, postal_code) on delete set null on update cascade);
my code is:
create database FullHouseGr1;
use FullHouseGr1;
create table Player
(player_id int not null,
first_name varchar(20) not null,
surname varchar(20) not null,
addres varchar(40) not null,
postal_code varchar(6) not null,
place varchar(40) not null,
phone_number varchar(20) not null,
email_addres varchar(255) not null,
points int not null,
primary key(player_id));
create table Location
(house_number int not null,
postal_code varchar(6) not null,
capacity int not null,
place varchar(40) not null,
street varchar(40) not null,
primary key(house_number, postal_code));
create table Poker_event
(date_time datetime not null,
min_players int not null,
max_players int not null,
house_number int not null,
postal_code varchar(6) not null,
primary key(date_time),
foreign key(house_number, postal_code) references Location(house_number, postal_code) on delete cascade on update cascade);
create table Tournament
(date_time datetime not null,
prize int not null,
primary key(date_time),
foreign key(date_time) references Poker_event(date_time) on delete no action on update cascade);
create table Tournament_round
(round_nr int not null,
date_time datetime not null,
primary key(date_time, round_nr),
foreign key(date_time) references Tournament(date_time) on delete no action on update cascade);
create table Tournament_table
(winner int not null,
date_time datetime not null,
round_nr int not null,
primary key(winner, date_time, round_nr),
foreign key(date_time) references Tournament(date_time) on delete no action on update cascade,
foreign key(round_nr) references Tournament(round_nr) on delete no action on update cascade);
create table Professional
(p_name varchar(40) not null,
primary key(name));
create table Masterclass
(date_time datetime not null,
min_rating int not null,
name varchar(40) not null,
primary key(date_time),
foreign key(p_name) references Professional(p_name) on delete no action on update cascade,
foreign key(date_time) references Poker_event(date_time) on delete no action on update cascade);
create table Poker_event_player
(date_time datetime not null,
has_payed boolean not null,
player_id int not null,
primary key(date_time, player_id),
foreign key(date_time) references Poker_event(date_time) on delete no action on update cascade,
foreign key(player_id) references Player on delete no action on update cascade);
create table Player_tournament_table
(winner int not null,
date_time datetime not null,
round_nr int not null,
player_id int not null,
primary key(winner, date_time, round_nr, player_id),
foreign key(winner) references Tournament_table on delete no action on update cascade,
foreign key(round_nr) references Tournament_round on delete no action on update cascade,
foreign key(date_time) references Tournament on delete no action on update cascade,
foreign key(player_id) references Player on delete no action on update cascade);

You're saying ON DELETE SET NULL but both of the fields in question are not nullable. Try ON DELETE CASCADE instead.
You can also check to make sure both tables are using the InnoDB engine.

Related

Can't create constraint key

I have these 3 MySQL tables:
Apps:
CREATE TABLE IF NOT EXISTS `apps` (
`identifier` INT NOT NULL AUTO_INCREMENT,
`id` VARCHAR(255) NOT NULL,
`name` VARCHAR(255) NULL,
`description` VARCHAR(255) NULL,
`cloud` VARCHAR(255) NULL,
`onpremise` VARCHAR(255) NULL,
`type` VARCHAR(255) NULL,
`editor` VARCHAR(255) NULL,
`provider` VARCHAR(255) NULL,
`administrators` INT NULL,
PRIMARY KEY(`identifier`),
CONSTRAINT admin_ref_team
FOREIGN KEY(`administrators`) REFERENCES `teams`(`identifier`)
ON DELETE CASCADE
ON UPDATE CASCADE
);
Quality:
CREATE TABLE IF NOT EXISTS `quality` (
`identifier` INT NOT NULL AUTO_INCREMENT,
`quality` VARCHAR(255) NOT NULL,
`label` VARCHAR(255) NOT NULL,
PRIMARY KEY(`identifier`)
);
Association of apps and quality:
CREATE TABLE IF NOT EXISTS `assoc_apps_quality` (
`identifier` INT NOT NULL AUTO_INCREMENT,
`apps_id` VARCHAR(255) NOT NULL,
`quality_id` INT NOT NULL,
PRIMARY KEY(`identifier`),
CONSTRAINT apps_ref_quality
FOREIGN KEY(`apps_id`) REFERENCES `apps`(`identifier`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT quality_ref_apps
FOREIGN KEY(`quality_id`) REFERENCES `quality`(`identifier`)
ON DELETE NO ACTION
ON UPDATE NO ACTION
);
Apps and Quality are created, but the third table is giving me this error and I can't create it:
Error in query (1215): Cannot add foreign key constraint
I don't see where is the problem. The constraint names are unique among all the database and there is no typos. Any ideas ?
Your apps_id defined in "quality_ref_apps" is wrong please try below sql.
CREATE TABLE IF NOT EXISTS `assoc_apps_quality` (
`identifier` INT NOT NULL AUTO_INCREMENT,
`apps_id` INT NOT NULL,
`quality_id` INT NOT NULL,
PRIMARY KEY(`identifier`),
CONSTRAINT apps_ref_quality
FOREIGN KEY(`apps_id`) REFERENCES `apps`(`identifier`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT quality_ref_apps
FOREIGN KEY(`quality_id`) REFERENCES `quality`(`identifier`)
ON DELETE NO ACTION
ON UPDATE NO ACTION
);
Change from apps_id VARCHAR(255) NOT NULL, TO apps_id INT NOT NULL,
Check data type.
FOREIGN KEY(`apps_id`) REFERENCES `apps`(`identifier`)
apps_id is VARCHAR,
identifier is INT

Error code:1215 Cannot add foreign key constraint while running script in MySQL workbench version 6.3

First of all i apologize that the names of the tables and so on are in another language.
The issue is i can't seem to add a foreign key named ID_KOPIE from the table KOPIA_KNIHY into the table SKLAD for some reason. When it gets to adding the foreign key to to the table SKLAD it throws out an error 1215. Here is the code:
CREATE TABLE BOOK (
BOOK_NAME VARCHAR(30) NOT NULL,
YEAR CHAR(4) NOT NULL,
NAME_OF_EDITOR VARCHAR(30) NOT NULL,
WRITER_ID INTEGER NOT NULL,
ISBN VARCHAR(17) NOT NULL,
BOOK_ID INTEGER NOT NULL,
PRIMARY KEY (BOOK_ID),
);
CREATE TABLE BOOK_COPY(
BOOK_ID INTEGER NOT NULL,
LANGUAGE_CODE CHAR(3) NOT NULL,
COPY_ID INTEGER NOT NULL,
BOOK_PICTURES CHAR(1) NOT NULL
CHECK (BOOK_PICTURES IN ("Y", "N")),
PRIMARY KEY (BOOK_ID, LANGUAGE_CODE, COPY_ID)
FOREIGN KEY(BOOK_ID)
REFERENCES BOOK(BOOK_ID),
);
CREATE TABLE STORAGE (
BOOK_ID INTEGER NOT NULL,
COPY_ID INTEGER NOT NULL,
BUILDING_ID INTEGER NOT NULL,
ROOM_NUMBER NUMERIC(4,0) NOT NULL,
SHELF_NUMBER NUMERIC(4,0) NOT NULL,
PRIMARY KEY(BOOK_ID, BUILDING_ID, COPY_ID),
FOREIGN KEY(COPY_ID)
REFERENCES BOOK_COPY(BOOK_ID),
)
I researched the error code 1215 on the internet, i couldn't find anything wrong with my database. I checked if there's a typo or if i didn't forget to add the reference.
This is the error:
0 769 18:19:37 CREATE TABLE STORAGE (
BOOK_ID INTEGER NOT NULL,
COPY_ID INTEGER NOT NULL,
BUILDING_ID INTEGER NOT NULL,
ROOM_NUMBER NUMERIC(4,0) NOT NULL,
SHELF_NUMBER NUMERIC(4,0) NOT NULL,
PRIMARY KEY(BOOK_ID, BUILDING_ID, COPY_ID),
FOREIGN KEY(COPY_ID)
REFERENCES BOOK_COPY(BOOK_ID),
)
Error Code: 1215. Cannot add foreign key constraint 0.016 sec
My question is how can this be fixed that it would work.
Help would be greatly appreciated.
Try this way. Please do alter the ON UPDATE ... ON DELETE syntax in this example with the one you need.
CREATE TABLE `KNIHA` (
`NAZOV_KNIHY` VARCHAR(30) NOT NULL,
`ROK_PRVEHO_VYDANIA` CHAR(4) NOT NULL,
`NAZOV_VYDAVATELA` VARCHAR(30) NOT NULL,
`ID_AUTORA` INTEGER NOT NULL,
`ISBN` VARCHAR(17) NOT NULL,
`ID_KNIHY` INTEGER NOT NULL,
PRIMARY KEY (`ID_KNIHY`)
);
CREATE TABLE `KOPIA_KNIHY` (
`ID_KNIHY` INTEGER NOT NULL,
`KOD_JAZYKA` CHAR(3) NOT NULL,
`ID_KOPIE` INTEGER NOT NULL,
`ORAZKY_V_KNIHE` CHAR(1) NOT NULL
CHECK (`OBRAZKY_V_KNIHE` IN ("A", "N")),
INDEX(`ID_KOPIE`),
PRIMARY KEY (`ID_KNIHY`, `KOD_JAZYKA`, `ID_KOPIE`),
CONSTRAINT `idx_1` FOREIGN KEY `idx_1` (`ID_KNIHY`) REFERENCES `KNIHA`(`ID_KNIHY`) ON UPDATE CASCADE ON DELETE CASCADE
);
CREATE TABLE `SKLAD` (
`ID_KNIHY` INTEGER NOT NULL,
`ID_KOPIE` INTEGER NOT NULL,
`ID_BUDOVY` INTEGER NOT NULL,
`CISLO_MIESTNOSTI` NUMERIC(4,0) NOT NULL,
`CISLO_REGALU` NUMERIC(4,0) NOT NULL,
PRIMARY KEY(`ID_KNIHY`, `ID_BUDOVY`, `ID_KOPIE`),
CONSTRAINT `idx_2` FOREIGN KEY `idx_2` (`ID_KOPIE`) REFERENCES `KOPIA_KNIHY`(`ID_KOPIE`) ON UPDATE CASCADE ON DELETE CASCADE,
CONSTRAINT `idx_3` FOREIGN KEY `idx_3` (`ID_KNIHY`) REFERENCES `KNIHA`(`ID_KNIHY`) ON UPDATE CASCADE ON DELETE CASCADE
);
Try it on SQL Fiddle
.

MySQL error:1251 cannot add foreign key

The first 4 table are created fine, the transactions tables run into problem. I get the 1215 error: cannot add foreign key. I've checked an rechecked the data types, and made sure all FK are PK of their own tables. What's wrong here?
CREATE SCHEMA FinalDB;
CREATE TABLE `User` (
userId int not null auto_increment primary key,
first_name varchar(255) not null,
last_name varchar(255) not null,
address varchar(255) null,
DOB date not null,
availableBalance int not null default 0,
currency varchar(20)
);
CREATE TABLE Verifications(
userId int not null primary key,
passport int null,
ssn int null,
license int null,
constraint
foreign key (userId)
references User(userId)
);
CREATE TABLE Linked_Account(
account_Id int not null,
userId int not null,
routing int null,
swift int null,
primary key (userId, account_Id),
constraint
foreign key (userId)
references User(userId)
);
CREATE TABLE Wallet (
userId int not null,
walletId varchar(5) not null,
coinAmount int not null default 0,
netWorth int not null default 0,
primary key(userId, walletId),
constraint
foreign key (userId)
references `User`(userId)
);
CREATE TABLE Transactions (
transactionId int not null primary key auto_increment,
userId int not null,
type varchar(30) not null,
walletId varchar(5) not null,
payment_method int null, #optional
total int null, #optional
quantity int not null,
fee int null, #optional
`date` date not null,
sender varchar(50) null, #optional
reciever varchar(50) null, #optional
status varchar(20) not null,
notes varchar(200) null, #optional
constraint
foreign key (userId)
references `User`(userId)
ON DELETE CASCADE ON UPDATE CASCADE,
constraint
foreign key (walletId)
references Wallet(walletId)
ON DELETE CASCADE ON UPDATE CASCADE,
constraint
foreign key (payment_method)
references Linked_Account(account_id)
);
CREATE TABLE TransactionsExchange(
transactionId int not null auto_increment primary key,
userId int not null,
currencyFrom int not null,
currencyFromAmount int not null,
currencyInto int not null,
currencyIntoEquivalent int not null,
notes varchar(200) null,
`date` date not null,
constraint
foreign key (userId)
references User(userId),
constraint
foreign key (currencyFrom)
references Wallet(walletId),
constraint
foreign key (currencyInto)
references Wallet(walletId)
);
I've look online for possible answer, but it's usually having to do with inconsistent data types or undeclared PK's. I'm basically trying to make a transactions table to log various different data in different compositions. Using backend logic to handle what is required and what is not, aside from a few defaults.
To use a compound Primary Key as Foreign Key, you'll have to add the
same number of columns (that compose the PK) with same datatypes to
the child table and then use the combination of these columns in the
FOREIGN KEY definition.
see related post here https://stackoverflow.com/a/10566463/4904726
Try this 'Transactions' table creating query:
CREATE TABLE Transactions (
transactionId int not null primary key auto_increment,
userId int not null,
type varchar(30) not null,
walletId varchar(5) not null,
payment_method int null, #optional
total int null, #optional
quantity int not null,
fee int null, #optional
`date` date not null,
sender varchar(50) null, #optional
reciever varchar(50) null, #optional
status varchar(20) not null,
notes varchar(200) null, #optional
constraint
foreign key (userId)
references `User`(userId)
ON DELETE CASCADE ON UPDATE CASCADE,
constraint
foreign key (userId, walletId)
references Wallet(userId, walletId)
ON DELETE CASCADE ON UPDATE CASCADE,
constraint
foreign key (userId, payment_method)
references Linked_Account(userId, account_id)
);

New to SQL, CREATE TABLE error

CREATE TABLE `ROUTE` (
`route_ID` INT NOT NULL,
`route_name` VARCHAR(45) NOT NULL,
`DELIVERY_VEHICLE_veh_ID` INT NOT NULL,
`DELIVERY_DRIVER_dr_ID` INT NOT NULL,
PRIMARY KEY (`route_ID`),
CONSTRAINT `fk_ROUTE_DELIVERY1`
FOREIGN KEY (`DELIVERY_VEHICLE_veh_ID` , `DELIVERY_DRIVER_dr_ID`)
(`VEHICLE_veh_ID` , `DRIVER_dr_ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION);
I'm new to SQL and trying to learn by practicing. There's an error in my syntax that I don't understand. Any help/suggestions?
(VEHICLE_veh_ID , DRIVER_dr_ID) at line 9
CREATE TABLE `DRIVER` (
`dr_ID` INT NOT NULL,
`dr_title` VARCHAR(15) NOT NULL,
`dr_fname` VARCHAR(45) NOT NULL,
`dr_lname` VARCHAR(45) NOT NULL,
`dr_DOB` DATETIME NOT NULL,
`dr_licenceNo` VARCHAR(45) NOT NULL,
`dr_phone` VARCHAR(15) NOT NULL,
`dr_email` VARCHAR(45) NOT NULL,
PRIMARY KEY (`dr_ID`));
CREATE TABLE `VEHICLE` (
`veh_ID` INT NOT NULL,
`veh_reg` VARCHAR(15) NOT NULL,
`veh_make` VARCHAR(45) NOT NULL,
`veh_model` VARCHAR(45) NOT NULL,
`veh_mileage` INT NOT NULL,
`veh_MOTdate` DATETIME NOT NULL,
`veh_servicedate` DATETIME NOT NULL,
PRIMARY KEY (`veh_ID`));
These are the other tables ROUTE is related to. I had no issues inserting DRIVER and VEHICLE tables into the DB, what's wrong with ROUTE?
It looks like there are two foreign keys in the ROUTE table.
One of them references the DRIVER table.
The other references the VEHICLE table.
Your foreign key constraint definitions should look more like this:
, CONSTRAINT `fk_ROUTE_DELIVERY_DRIVER`
FOREIGN KEY (`DELIVERY_DRIVER_dr_ID`)
REFERENCES `DRIVER` (`dr_ID`)
ON DELETE RESTRICT ON UPDATE RESTRICT
, CONSTRAINT `fk_ROUTE_DELIVERY_VEHICLE`
FOREIGN KEY (`DELIVERY_VEHICLE_veh_ID`)
REFERENCES `VEHICLE` (`veh_ID`)
ON DELETE RESTRICT ON UPDATE RESTRICT
CREATE TABLE `ROUTE` (
`route_ID` INT NOT NULL,
`route_name` VARCHAR(45) NOT NULL,
`DELIVERY_VEHICLE_veh_ID` INT NOT NULL,
`DELIVERY_DRIVER_dr_ID` INT NOT NULL,
PRIMARY KEY (`route_ID`),
CONSTRAINT `fk_ROUTE_VEHICLE`
FOREIGN KEY (`DELIVERY_VEHICLE_veh_ID`)
REFERENCES `VEHICLE`(`veh_ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_ROUTE_DRIVER`
FOREIGN KEY (`DELIVERY_DRIVER_dr_ID`)
REFERENCES `DRIVER`(`dr_ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION);

Syntax Error while creating a table in SQL

I am trying this query and despite several attempts, I am still getting a syntax error when I create Table Call. The other tables get created just fine.. I don't understand why
Code for Student
CREATE TABLE Student (
`student_id` int NOT NULL AUTO_INCREMENT,
`phone_number` varchar(50) NOT NULL,
`name` varchar(50) NOT NULL,
`school` varchar(50) NOT NULL,
`class` varchar(50) NOT NULL,
PRIMARY KEY (`student_id`)
)
Table Stories
CREATE TABLE Stories (
`story_id` int NOT NULL AUTO_INCREMENT,
`story_name` varchar(50) NOT NULL,
`number_questions` int NOT NULL,
`file_name` varchar(100) NOT NULL,
PRIMARY KEY (`story_id`)
)
Table Questions
CREATE TABLE Questions (
`question_id` int NOT NULL,
`story_id` int NOT NULL,
`file_name` varchar(100) NOT NULL,
`concept_tested` varchar(100) NOT NULL,
`difficuly` varchar(50) NOT NULL,
`number_options` int NOT NULL,
`correct_answer` int NOT NULL,
`call_number` int NOT NULL,
PRIMARY KEY (`question_id`,`story_id`),
FOREIGN KEY (`story_id`)
REFERENCES `Stories`(`story_id`)
ON DELETE CASCADE
)
Table Call
CREATE TABLE Call (
`call_id` int NOT NULL AUTO_INCREMENT,
`student_id` int NOT NULL,
`story_id` int NOT NULL,
`question_id` int NOT NULL,
`call_number` int NOT NULL,
`total_number` int NOT NULL,
PRIMARY KEY (`call_id`),
FOREIGN KEY (`student_id`)
REFERENCES `Student`(`story_id`)
ON DELETE CASCADE,
FOREIGN KEY (`story_id`)
REFERENCES `Stories`(`student_id`)
ON DELETE CASCADE,
FOREIGN KEY (`question_id`)
REFERENCES `Stories`(`question_id`)
ON DELETE CASCADE
)
Here is my error:
#1064 - 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 'Call ( `call_id` int NOT NULL AUTO_INCREMENT, `student_id` int NOT NULL, ' at line 1
I have tried editing my code and checking it several times but the problem remains unsolved
I solved the problem,
It is:
CREATE TABLE `Call` (
`call_id` int NOT NULL AUTO_INCREMENT,
`student_id` int NOT NULL,
`story_id` int NOT NULL,
`question_id` int NOT NULL,
`call_number` int NOT NULL,
`total_number` int NOT NULL,
PRIMARY KEY (`call_id`),
FOREIGN KEY (`student_id`)
REFERENCES `Student`(`student_id`)
ON DELETE CASCADE,
FOREIGN KEY (`story_id`)
REFERENCES `Stories`(`story_id`)
ON DELETE CASCADE,
FOREIGN KEY (`question_id`)
REFERENCES `Questions`(`question_id`)
ON DELETE CASCADE
)
I found that these conditions must be satisfied to not get error 150:
The two tables must be ENGINE=InnoDB. (can be others: ENGINE=MyISAM works too)
The two tables must have the same charset.
The PK column(s) in the parent table and the FK column(s) must be the same data type.
The PK column(s) in the parent table and the FK column(s), if they have a define collation type, must have the same collation type;
If there is data already in the foreign key table, the FK column value(s) must match values in the parent table PK columns.
And the child table cannot be a temporary table.
Hope this helps.
Try like this
CREATE TABLE Questions (
`call_id` int NOT NULL AUTO_INCREMENT,
`student_id` int NOT NULL,
`story_id` int NOT NULL,
`question_id` int NOT NULL,
`call_number` int NOT NULL,
`total_number` int NOT NULL,
PRIMARY KEY (`call_id`),
FOREIGN KEY (`student_id`)
REFERENCES `Student`(`story_id`)
ON DELETE CASCADE,
FOREIGN KEY (`story_id`)
REFERENCES `Stories`(`student_id`)
ON DELETE CASCADE,
FOREIGN KEY (`question_id`)
REFERENCES `Stories`(`question_id`)
ON DELETE CASCADE
)ENGINE=MYISAM CHARACTER SET UTF8;
FIDDLE DEMO
Take a look at here