Mysql can not add foreign key - mysql

I have a study case where three tables has to be created. there creation statements are as following.
create table COMMUNITY(
c_id varchar(10) primary key,
name varchar(30) not null,
longitude float,
latitude float,
post_code varchar(15) not null,
key(c_id))
create table UNIT(
c_id varchar(10) not null,
u_id int not null,
name varchar(20) not null,
key(c_id, u_id),
primary key(c_id, u_id),
constraint unique(c_id, u_id),
constraint FK_UNIT foreign key(c_id) references COMMUNITY(c_id)
on delete cascade on update cascade)
create table ROOM(
r_id int not null,
u_id int not null,
c_id varchar(10) not null,
name varchar(20),
primary key(c_id, u_id, r_id),
constraint FK_ROOM_UID foreign key(u_id) references UNIT(u_id)
on delete cascade on update cascade,
constraint FK_ROOM_CID foreign key(c_id) references UNIT(c_id)
on delete cascade on update cascade)
the Community and unit tables are created successfully, but when I try to create room, mysql gives me Error Code: 1215. Cannot add foreign key constraint
I wonder what's going here and How I can create them? (I knew InnoDB can solve this problem, but is there any other way I can do that?)
Thanks

This looks like the culprit of the actual error you're seeing:
constraint FK_ROOM_UID foreign key(u_id) references UNIT(u_id)
constraint FK_ROOM_UID foreign key(c_id) references UNIT(c_id)
It should be:
constraint FK_ROOM_UID foreign key(c_id, u_id) references UNIT(c_id, u_id)
Referencing the double-column key in the UNIT table
You'll also need to use InnoDB to actually create the foreign key indexes, so:
CREATE TABLE UNIT(
....
) ENGINE=InnoDB;

I finally fugured this out, according to the MySQL log
"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."
All I have to do is to create primary key at the first column of a table and make sure the type matches. so I changed my statements as following
create table UNIT(
primary key(c_id, u_id),
c_id varchar(10) not null,
u_id int not null,
name varchar(20) not null,
constraint unique(c_id, u_id),
constraint FK_UNIT foreign key(c_id) references COMMUNITY(c_id)
on delete cascade on update cascade)
create table ROOM(
primary key(c_id, u_id, r_id),
r_id int not null,
u_id int not null,
c_id varchar(10) not null,
name varchar(20),
constraint FK_ROOM_UID foreign key(c_id, u_id)
references UNIT(c_id, u_id) on delete cascade on update cascade)
Now I can create tables properly. I have been struggling on this problem since yesterday.

Related

what is the problem with my tables in mysql?

I'm going to create 3 table. table "post" and "taxonomy" are connected to "taxonomy_relationship" table with primary key and foreign key but i don't know why do i get this error:
1005 - Can't create table taxonomy_relationship (errno: 150 "Foreign key constraint is incorrectly formed")
CREATE TABLE `post`(
id int not null AUTO_INCREMENT,
title varchar(255) not null,
content TEXT not null,
PRIMARY KEY(id)
);
CREATE TABLE `taxonomy`(
id int not null AUTO_INCREMENT,
tax_title varchar(255) not null,
type varchar(255) not null,
PRIMARY KEY(id, tax_title)
);
CREATE TABLE taxonomy_relationship(
id INT AUTO_INCREMENT,
post_id int not null,
title varchar(255) not null,
PRIMARY KEY(id),
FOREIGN KEY (post_id)
REFERENCES post(id)
ON DELETE CASCADE
ON UPDATE CASCADE
FOREIGN KEY (title)
REFERENCES taxonomy(tax_title)
ON DELETE CASCADE
ON UPDATE CASCADE
);
when i use "SHOW ENGINE INNODB STATUS" to show error details it returns:
>
2020-01-19 16:08:31 0x2fb8 Error in foreign key constraint of table blog.taxonomy_relationship:
FOREIGN KEY (title)
REFERENCES taxonomy(tax_title)
ON DELETE CASCADE
ON UPDATE CASCADE
):
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.
Please refer to https://mariadb.com/kb/en/library/foreign-keys/ for correct foreign key definition.
Create table blog.taxonomy_relationship with foreign key constraint failed. There is no index in the referenced table where the referenced columns appear as the first columns near 'FOREIGN KEY (title)
REFERENCES taxonomy(tax_title)
ON DELETE CASCADE
ON UPDATE CASCADE
)'.
You should to add index KEY title_idx (tax_title) on taxonomy table :
CREATE TABLE `taxonomy` (
`id` int NOT NULL AUTO_INCREMENT,
`tax_title` varchar(255) NOT NULL,
`type` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
KEY `title_idx` (`tax_title`)
);
After you can create foreign key:
CREATE TABLE taxonomy_relationship(
id INT AUTO_INCREMENT,
post_id int not null,
title varchar(255) not null,
PRIMARY KEY(id),
FOREIGN KEY (post_id)
REFERENCES post(id)
ON DELETE CASCADE
ON UPDATE CASCADE,
FOREIGN KEY (title)
REFERENCES taxonomy(tax_title)
ON DELETE CASCADE
ON UPDATE CASCADE
);
Another way you can duplicate title in taxonomy_relationship but link it by id field:
CREATE TABLE taxonomy_relationship(
id INT AUTO_INCREMENT,
post_id int not null,
taxonomy_id int not null,
PRIMARY KEY(id),
FOREIGN KEY (post_id)
REFERENCES post(id)
ON DELETE CASCADE
ON UPDATE CASCADE,
FOREIGN KEY (taxonomy_id)
REFERENCES taxonomy(id)
ON DELETE CASCADE
ON UPDATE CASCADE
);

Error on add foreign key constraint

Every time I'm trying to insert a foreign key to the table I got that message:
Error Code: 1215. Cannot add foreign key constraint 0.281 sec
My create table code:
CREATE TABLE `test`.`buy`(
`id` INT NOT NULL AUTO_INCREMENT,
`id_customer` INT UNSIGNED NOT NULL,
`code` VARCHAR(45) NOT NULL,
PRIMARY KEY(`id`),
UNIQUE INDEX `code_UNIQUE`(`code`),
CONSTRAINT `id_customer` FOREIGN KEY(`id_customer`) REFERENCES `test`.`customer`(`id_customer`) ON DELETE RESTRICT ON UPDATE CASCADE,
CONSTRAINT `code` FOREIGN KEY(`code`) REFERENCES `test`.`product`(`code`) ON DELETE RESTRICT ON UPDATE CASCADE
)
What should I do ?
Please format your code next time so it's easier to read.
You don't need the CONSTRAINT xxx bit, try this instead:
CREATE TABLE test.buy (
id INT NOT NULL AUTO_INCREMENT,
id_customer INT UNSIGNED NOT NULL,
code VARCHAR(45) NOT NULL,
PRIMARY KEY (id),
UNIQUE INDEX code_UNIQUE (code),
FOREIGN KEY (id_customer)
REFERENCES test.customer (id_customer)
ON DELETE RESTRICT ON UPDATE CASCADE,
FOREIGN KEY (code)
REFERENCES test.product (code)
ON DELETE RESTRICT ON UPDATE CASCADE
);
If that still doesn't work then make sure the other tables you reference (test.customer and test.product) already exist and that they have matching fields of the same data type.

MySQL: Cannot add foreign key constraint error in school project

I'm building a really basic database for a school project and am getting a "cannot add foreign key constraint" error in MySQL. I've been scratching my head on this one for the past day, read all of the related posts and haven't been able to figure it out.
Here are the first two tables of my project:
CREATE TABLE CUSTOMER (
CUST_ID INTEGER NOT NULL AUTO_INCREMENT UNIQUE,
CUST_LNAME VARCHAR(25) NOT NULL,
CUST_FNAME VARCHAR(25) NOT NULL,
CUST_INITIAL CHAR(1),
CUST_STREET_NO VARCHAR(6),
CUST_STREET_NAME VARCHAR(25),
CUST_APT_NO VARCHAR(10),
CUST_CITY VARCHAR(25),
CUST_STATE CHAR(2),
CUST_ZIP_CODE CHAR(5),
CUST_HOME_AC CHAR(3),
CUST_HOME_PHONE CHAR(8),
PRIMARY KEY (CUST_ID))
ENGINE = InnoDB;
CREATE TABLE INVOICE (
INVOICE_ID INTEGER NOT NULL AUTO_INCREMENT UNIQUE,
CUST_ID INTEGER NOT NULL,
INV_DATE DATE NOT NULL,
SPECIAL_HANDLING VARCHAR(35),
PRIMARY KEY (INVOICE_ID),
FOREIGN KEY (CUST_ID) REFERENCES CUSTOMER ON UPDATE CASCADE)
ENGINE = InnoDB;
I'm sure it's something super easy that I'm missing. Any ideas?
You are missing the column to be referred in your foreign key constraint def.
Use:
FOREIGN KEY (CUST_ID) REFERENCES CUSTOMER(CUST_ID) ON UPDATE CASCADE)
instead of
FOREIGN KEY (CUST_ID) REFERENCES CUSTOMER ON UPDATE CASCADE)
So, create table becomes:
CREATE TABLE INVOICE (
INVOICE_ID INTEGER NOT NULL AUTO_INCREMENT UNIQUE,
CUST_ID INTEGER NOT NULL,
INV_DATE DATE NOT NULL,
SPECIAL_HANDLING VARCHAR(35),
PRIMARY KEY (INVOICE_ID),
FOREIGN KEY (CUST_ID) REFERENCES CUSTOMER(CUST_ID) ON UPDATE CASCADE)
ENGINE = InnoDB;
try to declare the name of the foreign key, and then declare the column of the current table and the table and the reference column
CONSTRAINT fk_customer FOREIGN KEY (INVOICE_ID)
REFERENCES customer(CUST_ID)

Cannot add foreign key constraint - data types match

i am trying to do alter like this
alter table user_position
add constraint fk_user_position_user
foreign key (id_user)
references users(id_user),
add constraint fk_user_position_waypoint
foreign key (id_waypoint)
references waypoint(id_waypoint);
But i get this error:Error Code: 1215. Cannot add foreign key constraint
I check columns data types and they all match -
users.id_user int(11)= user_position.id_user int(11)
waypoint.id_waypoint int(11)=user_position.id_waypoint int(11)
I´m getting this error on both alters separatelly when i try it
I am running on MySql database, command executed in MySql Workbench
DDL for all tables:
/*
Created 29. 7. 2013
Modified 30. 7. 2013
Project
Model
Company
Author
Version
Database mySQL 5
*/
Create table Users (
id_user Int NOT NULL,
username Char(20),
pass Char(20),
Primary Key (id_user)) ENGINE = MyISAM;
Create table Waypoint (
id_waypoint Int NOT NULL,
id_user Int NOT NULL,
name Char(20),
description Char(20),
priority Int,
type_number Int,
Primary Key (id_waypoint,id_user)) ENGINE = MyISAM;
Create table Message (
text Text,
id_message_type Int NOT NULL,
shown Bool,
id_message Int NOT NULL,
id_user Int NOT NULL,
Primary Key (id_message_type,id_message,id_user)) ENGINE = MyISAM;
Create table Message_Type (
id_message_type Int NOT NULL,
description Char(20),
Primary Key (id_message_type)) ENGINE = MyISAM;
Create table User_group (
id_user_group Int NOT NULL,
description Char(20),
id_user_rights Char(20) NOT NULL,
Primary Key (id_user_group,id_user_rights)) ENGINE = MyISAM;
Create table User_Rights (
id_user_rights Char(20) NOT NULL,
description Char(20),
kod Char(20),
Primary Key (id_user_rights)) ENGINE = MyISAM;
Create table Permisions (
id_permision Char(20) NOT NULL,
description Char(20),
Primary Key (id_permision)) ENGINE = MyISAM;
Create table UserRightPermisions (
id_user_rights Char(20) NOT NULL,
id_permision Char(20) NOT NULL,
Primary Key (id_permision)) ENGINE = MyISAM;
Create table User_Set_Of_Groups (
id_user_group Int NOT NULL,
id_user_rights Char(20) NOT NULL,
id_user Int NOT NULL,
is_main Bool,
Primary Key (id_user_group,id_user_rights,id_user)) ENGINE = MyISAM;
Alter table Waypoint add Foreign Key (id_user) references Users (id_user) on delete restrict on update restrict;
Alter table Message add Foreign Key (id_user) references Users (id_user) on delete restrict on update restrict;
Alter table User_Set_Of_Groups add Foreign Key (id_user) references Users (id_user) on delete restrict on update restrict;
Alter table Message add Foreign Key (id_message_type) references Message_Type (id_message_type) on delete restrict on update restrict;
Alter table User_Set_Of_Groups add Foreign Key (id_user_group,id_user_rights) references User_group (id_user_group,id_user_rights) on delete restrict on update restrict;
Alter table User_group add Foreign Key (id_user_rights) references User_Rights (id_user_rights) on delete restrict on update restrict;
Alter table UserRightPermisions add Foreign Key (id_user_rights) references User_Rights (id_user_rights) on delete restrict on update restrict;
Alter table UserRightPermisions add Foreign Key (id_permision) references Permisions (id_permision) on delete restrict on update restrict;
The foreign key must refer to the primary (or unique) key
The columns data types must be exactly the same (check NOT NULL, UNSIGNED etc)

multiple foreign keys cannot be added

I am wondering why i cannot be able to add this foreign keys.This is my schema
CREATE TABLE members(
member_id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(50) NOT NULL,
num_1 int,
num_2 int,
password VARCHAR(50) NOT NULL,
PRIMARY KEY (member_id)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE contacts(
contact_id INT NOT NULL AUTO_INCREMENT,
s1 int,
phone_number VARCHAR(10) NOT NULL,
s2 int,
s3 int,
PRIMARY KEY (contact_id),
FOREIGN KEY (s1) REFERENCES members(num_1) ON DELETE CASCADE ON UPDATE CASCADE,
FOREIGN KEY (s2) REFERENCES members(num_2) ON DELETE CASCADE ON UPDATE CASCADE,
FOREIGN KEY (s3) REFERENCES members(member_id) ON DELETE CASCADE ON UPDATE CASCADE
)ENGINE=InnoDB DEFAULT CHARSET=utf8
I get this error on the mysql terminal
ERROR 1215 (HY000): Cannot add foreign key constraint
Is there a problem with my schema?.
Works for me this way:
CREATE TABLE members(
member_id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(50) NOT NULL,
num_1 int,
num_2 int,
password VARCHAR(50) NOT NULL,
PRIMARY KEY (member_id),
key idx_num1 (num_1),
key idx_num2 (num_2)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE contacts(
contact_id INT NOT NULL AUTO_INCREMENT,
s1 int,
phone_number VARCHAR(10) NOT NULL,
s2 int,
s3 int,
PRIMARY KEY (contact_id),
FOREIGN KEY (s1) REFERENCES members(num_1) ON DELETE CASCADE ON UPDATE CASCADE,
FOREIGN KEY (s2) REFERENCES members(num_2) ON DELETE CASCADE ON UPDATE CASCADE,
FOREIGN KEY (s3) REFERENCES members(member_id) ON DELETE CASCADE ON UPDATE CASCADE
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
Just added
key idx_num1 (num_1),
key idx_num2 (num_2)
in table members. Foreign keys need to reference an indexed column (not necessarily unique and not necessarily NOT NULLable).
From the manual:
InnoDB permits a foreign key to reference any index column or group of columns. However, in the referenced table, there must be an index where the referenced columns are listed as the first columns in the same order.