simple tables -ERROR 1215: Cannot add foreign key constraint, - mysql

I have these two simple table
CREATE TABLE `location_main_master` (
`location_main_master_id` bigint(16) unsigned NOT NULL,
`city_id_test` int(10) unsigned NOT NULL,
PRIMARY KEY (`location_main_master_id`,`city_id_test`),
UNIQUE KEY `location_main_master_id_UNIQUE` (`location_main_master_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `location_sub_master` (
`location_sub_master_id` bigint(16) unsigned NOT NULL,
`city_id` int(10) unsigned NOT NULL,
PRIMARY KEY (`location_sub_master_id`,`city_id`),
UNIQUE KEY `location_sub_master_id_UNIQUE` (`location_sub_master_id`),
KEY `fk_location_sub_master_city_id_idx` (`city_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
I'm trying to add a foreign key
ALTER TABLE `location_sub_master`
ADD CONSTRAINT `fk_location_sub_city_id`
FOREIGN KEY (`city_id`)
REFERENCES `location_main_master` (`city_id_test`)
ON DELETE NO ACTION
ON UPDATE NO ACTION;
It give me this ERROR :
ERROR 1215: Cannot add foreign key constraint

You have to change the order of your primary key in master table.
PRIMARY KEY (city_id_test,location_main_master_id)
So your master table should look like
CREATE TABLE location_main_master (
location_main_master_id BIGINT(16) UNSIGNED NOT NULL,
city_id_test INT(10) UNSIGNED NOT NULL,
PRIMARY KEY (city_id_test,location_main_master_id),
UNIQUE KEY location_main_master_id_UNIQUE (location_main_master_id)
) ENGINE=INNODB DEFAULT CHARSET=utf8;

Related

How to create composite foreign key in Mysql

I need to add composite foreign key to table which structure looks like
CREATE TABLE IF NOT EXISTS `discount_month_devices` (
`id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`discount_month_id` int(11) UNSIGNED NOT NULL,
`global_device_id` int(11) DEFAULT NULL,
`location_id` int(11) UNSIGNED DEFAULT NULL,
`server_id` varchar(20) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `discount_month_id` (`discount_month_id`),
KEY `global_device_id` (`global_device_id`),
KEY `location_id` (`location_id`,`server_id`),
KEY `server_id` (`server_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
Devices table DDL looks like
CREATE TABLE IF NOT EXISTS `devices` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`server_id` varchar(20) CHARACTER SET utf8mb4 NOT NULL,
`device_id` int(11) DEFAULT NULL,
`location_id` int(11) UNSIGNED DEFAULT NULL,
`device_lat` float DEFAULT NULL,
`device_long` float DEFAULT NULL,
....
PRIMARY KEY (`id`) USING BTREE,
UNIQUE KEY `devices_idx1` (`server_id`,`device_id`) USING BTREE,
KEY `devices_idx5` (`server_id`) USING BTREE,
KEY `devices_idx6` (`device_id`) USING BTREE,
KEY `devices_idx8` (`server_id`,`owner_id`) USING BTREE,
KEY `server_id` (`server_id`,`location_id`),
KEY `devices_idx14` (`location_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1583586 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci ROW_FORMAT=DYNAMIC;
ALTER TABLE `devices`
ADD CONSTRAINT `devices_fk1` FOREIGN KEY (`server_id`,`location_id`) REFERENCES `locations` (`server_id`, `location_id`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `devices_fk2` FOREIGN KEY (`discount_month_id`) REFERENCES `discount_month` (`id`);
There are location_id composite index. I can create FK for location_id and server_id separately so columns types and ranges should be right.
I would like to run alter table which should add the foreign which looks like
ALTER TABLE `discount_month_devices` ADD CONSTRAINT `discount_month_devices_fk3`
FOREIGN KEY (`location_id`, `server_id`) REFERENCES `devices`(`location_id`, `server_id`)
ON DELETE CASCADE ON UPDATE CASCADE;
This throws me an error: General error: 1215 Cannot add foreign key constraint
Does anybody know what could be the problem.
You must list the columns in the foreign key constraint in the same order that they appear in a key in the referenced table. Your key in devices is on (server_id, location_id) but you tried to reference them in your foreign key constraint as (location_id, server_id).
Try this:
ALTER TABLE `discount_month_devices`
ADD CONSTRAINT `discount_month_devices_fk3`
FOREIGN KEY (`server_id`, `location_id`)
REFERENCES `devices`(`server_id`, `location_id`)
ON DELETE CASCADE ON UPDATE CASCADE;
The order of columns in keys and constraints is not required to match the order of columns in the table definition.

Error Code: 1822. Failed to add the foreign key constraint

CREATE TABLE `branch` (
`BranchID` INT NOT NULL,
`BranchSuburb` varchar(255) NOT NULL,
`BranchState` char(3) NOT NULL,
PRIMARY KEY (`BranchID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `member` (
`MemberID` INT NOT NULL,
`MemberStatus` char(9) DEFAULT 'REGULAR',
`MemberName` varchar(255) NOT NULL,
`MemberAddress` varchar(255) NOT NULL,
`MemberSuburb` varchar(25) NOT NULL,
`MemberState` char(3) NOT NULL,
`MemberExpDate` DATE,
`MemberPhone` varchar(10),
PRIMARY KEY (`MemberID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `publisher` (
`PublisherID` INT NOT NULL,
`PublisherName` varchar(255) NOT NULL,
`PublisherAddress` varchar(255) DEFAULT NULL,
PRIMARY KEY (`PublisherID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `book` (
`BookID` INT NOT NULL,
`BookTitle` varchar(255) NOT NULL,
`PublisherID` INT NOT NULL,
`PublishedYear` INT4,
`Price` Numeric(5,2) NOT NULL,
PRIMARY KEY (`BookID`),
KEY `PublisherID` (`PublisherID`),
CONSTRAINT `publisher_fk_1` FOREIGN KEY (`PublisherID`) REFERENCES `publisher` (`PublisherID`) ON DELETE RESTRICT
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `author` (
`AuthorID` INT NOT NULL,
`AuthorName` varchar(255) NOT NULL,
`AuthorAddress` varchar(255) NOT NULL,
PRIMARY KEY (`AuthorID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `authoredby` (
`BookID` INT NOT NULL,
`AuthorID` INT NOT NULL,
PRIMARY KEY (`BookID`,`AuthorID`),
KEY `bookID` (`BookID`),
KEY `AuthorID` (`AuthorID`),
CONSTRAINT `book_fk_1` FOREIGN KEY (`BookID`) REFERENCES `book` (`bookID`) ON DELETE RESTRICT,
CONSTRAINT `author_fk_1` FOREIGN KEY (`AuthorID`) REFERENCES `author` (`AuthorID`) ON DELETE RESTRICT
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `holding` (
`BranchID` INT NOT NULL,
`BookID` INT NOT NULL,
`InStock` INT DEFAULT 1,
`OnLoan` INT DEFAULT 0,
PRIMARY KEY (`BranchID`,`BookID`),
KEY `bookID` (`BookID`),
KEY `BranchID` (`BranchID`),
CONSTRAINT `holding_cc_1` CHECK(`InStock`>=`OnLoan`),
CONSTRAINT `book_fk_2` FOREIGN KEY (`BookID`) REFERENCES `book` (`bookID`) ON DELETE RESTRICT,
CONSTRAINT `branch_fk_1` FOREIGN KEY (`BranchID`) REFERENCES `branch` (`BranchID`) ON DELETE RESTRICT
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `borrowedby` (
`BookIssueID` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`BranchID` INT NOT NULL,
`BookID` INT NOT NULL,
`MemberID` INT NOT NULL,
`DateBorrowed` DATE,
`DateReturned` DATE DEFAULT NULL,
`ReturnDueDate` DATE,
PRIMARY KEY (`BookIssueID`),
KEY `bookID` (`BookID`),
KEY `BranchID` (`BranchID`),
KEY `MemberID` (`MemberID`),
CONSTRAINT `borrowedby_cc_1` CHECK(`DateBorrowed`<`ReturnDueDate`),
CONSTRAINT `holding_fk_1` FOREIGN KEY (`BookID`,`BranchID`) REFERENCES `holding` (`BookID`,`BranchID`) ON DELETE RESTRICT,
CONSTRAINT `member_fk_1` FOREIGN KEY (`MemberID`) REFERENCES `member` (`MemberID`) ON DELETE RESTRICT
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Im getting the following error when i try to execute the last create query for the borrowedby table.
Error Code: 1822. Failed to add the foreign key constraint. Missing index for constraint 'holding_fk_1' in the referenced table 'holding'
have you tried to split the double foreign key? like this:
CONSTRAINT `holding_fk_1` FOREIGN KEY (`BookID`) REFERENCES `holding` (`BookID`) ON DELETE RESTRICT,
CONSTRAINT `holding_fk_1` FOREIGN KEY (`BranchID`) REFERENCES `holding` (`BranchID`) ON DELETE RESTRICT
what dms are you using? could be that you need to use another syntax to reference two foreign key at one or could be that it's not supported.
As said in the answer, just by changing order can fix it.
"Your code fails in Mysql 8.0.12 but runs fine in 8.0.22 As a workaround reverse the order of the columns: CONSTRAINT holding_fk_1 FOREIGN KEY (BranchID,BookID) REFERENCES holding (BranchID,BookID) ON DELETE RESTRICT, –
forpas
Oct 27 '20 at 15:50 "

Workbench MySQL: table is not editable

I have the following table:
CREATE TABLE `cat_matches` (
`from_cat` int(11) NOT NULL,
`to_cat` int(11) NOT NULL,
`tag` char(10) DEFAULT NULL,
`id` int(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`),
UNIQUE KEY `id` (`id`),
KEY `cat_matches_ibfk_1` (`from_cat`),
KEY `cat_matches_ibfk_2` (`to_cat`),
CONSTRAINT `cat_matches_ibfk_1` FOREIGN KEY (`from_cat`) REFERENCES `category` (`id`),
CONSTRAINT `cat_matches_ibfk_2` FOREIGN KEY (`to_cat`) REFERENCES `category` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2519 DEFAULT CHARSET=latin1
In a lot of other threads, people reply "in Workbench the table have to have a PK to be editable". But as you can see, this table contains a column called id which is the PK, and is still not editable. Why?

Why can't I add a foreign key constraint this way?

Tables:
CREATE TABLE `relation` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(40) NOT NULL,
`gender` tinyint(1) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `unique_relation` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
CREATE TABLE `invite` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`date_sent` date NOT NULL,
`user_id` int(10) unsigned NOT NULL,
`relation_id` int(10) unsigned NOT NULL,
`email` varchar(255) NOT NULL,
`code` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
KEY `fk_user` (`user_id`),
CONSTRAINT `fk_user` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8
The SQL statement executed was:
ALTER TABLE `invite`
ADD CONSTRAINT `fk_relation`
FOREIGN KEY (`relation_id`)
REFERENCES `relation` (`id`)
ON DELETE CASCADE ON UPDATE RESTRICT
Mysql Error:
SQLSTATE[HY000]: General error: 1005 Can't create table 'dbtest.#sql-d00_39' (errno: 121).
The relation.id and invite.relation_id columns are of the same type int(10) unsigned
UPDATE
The table invite is empty while adding this key.
The table relation has 3 rows.
try this :
ALTER TABLE invite
ADD CONSTRAINT fk_relation
FOREIGN KEY (relation_id)
REFERENCES relation(id)
According to the doc syntax is correct SQL FOREIGN KEY Constraint
The DDL for Foreign Key creation now automatically includes statements to specify actions on "Delete" and "Update". However, for "Delete", it includes the statement "ON DELETE RESTRICT", which does not appear to be a valid T-SQL statement.
TRY THIS :
ALTER TABLE invite WITH CHECK ADD CONSTRAINT fk_relation
FOREIGN KEY (relation_id) REFERENCES relation (id)

Mysql FOREIGN KEY error 150

CREATE TABLE IF NOT EXISTS `questions` (
`question_id` int(11) NOT NULL AUTO_INCREMENT,
`createddate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updateddate` timestamp NULL DEFAULT NULL,
`active_flag` tinyint(4) NOT NULL DEFAULT '0',
PRIMARY KEY (`question_id`),
UNIQUE KEY `id_UNIQUE` (`question_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
CREATE TABLE `alarts` (
`alart_id` BIGINT(20) unsigned NOT NULL AUTO_INCREMENT,
`alart_name` varchar(45) NOT NULL,
`interval` int(10) unsigned NOT NULL,
`alart_sent_counter` int(10) unsigned NOT NULL,
`alart_types_id` BIGINT(20) unsigned NOT NULL,
`contact_group_id` int(10) unsigned NOT NULL,
PRIMARY KEY (`alart_id`),
FOREIGN KEY (`alart_types_id`) REFERENCES alart_types(`alart_types_id`)
) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=utf8;
I want to create new table with two FOREIGN KEY like this:
CREATE TABLE `alart_question_mapping` (
`alart_question_mapping_id` BIGINT(20) unsigned NOT NULL AUTO_INCREMENT,
`question_id` int(11) NOT NULL,
`alart_id` BIGINT(20) unsigned NOT NULL,
PRIMARY KEY (`alart_question_mapping_id`),
FOREIGN KEY (`question_id`) REFERENCES questions(`question_id`),
FOREIGN KEY (`alart_id`) REFERENCES alart_types(`alart_id`)
) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=utf8;
but I am getting error:
Error Code: 1005. Can't create table 'alart_question_mapping' (errno: 150)
How can I create this table ?
Thank's.
Chane the statement:
FOREIGN KEY (`alart_id`) REFERENCES alart_types(`alart_id`)
to
FOREIGN KEY (`alart_id`) REFERENCES alarts(`alart_id`)
The only thing I can see is you are referencing a table in your CREATE TABLE statement that is not present in what you provided:
FOREIGN KEY (`alart_id`) REFERENCES alart_types(`alart_id`)
If you remove this reference the table will create. See SQL Fiddle with Demo
Edit #1, based on your update the problem is you are referencing the wrong field in your last table:
Change this:
CREATE TABLE `alart_question_mapping` (
`alart_question_mapping_id` BIGINT(20) unsigned NOT NULL AUTO_INCREMENT,
`question_id` int(11) NOT NULL,
`alart_id` BIGINT(20) unsigned NOT NULL,
PRIMARY KEY (`alart_question_mapping_id`),
FOREIGN KEY (`question_id`) REFERENCES questions(`question_id`),
FOREIGN KEY (`alart_id`) REFERENCES alart_types(`alart_id`)
)
To this:
CREATE TABLE `alart_question_mapping` (
`alart_question_mapping_id` BIGINT(20) unsigned NOT NULL AUTO_INCREMENT,
`question_id` int(11) NOT NULL,
`alart_id` BIGINT(20) unsigned NOT NULL,
PRIMARY KEY (`alart_question_mapping_id`),
FOREIGN KEY (`question_id`) REFERENCES questions(`question_id`),
FOREIGN KEY (`alart_id`) REFERENCES alart_types(`alart_types_id`)
) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=utf8;
So you are changing this line:
FOREIGN KEY (`alart_id`) REFERENCES alart_types(`alart_id`)
to this:
FOREIGN KEY (`alart_id`) REFERENCES alart_types(`alart_types_id`)
If you are referencing the alart_types table then you will want to reference the alart_types_id not the alart_id
see SQL Fiddle with Demo
It can't find table alart_types.
From MySQL Foreign Key Constraints
If you re-create a table that was dropped, it must have a definition
that conforms to the foreign key constraints referencing it. It must
have the right column names and types, and it must have indexes on the
referenced keys, as stated earlier. If these are not satisfied, MySQL
returns error number 1005 and refers to error 150 in the error
message.
I think you mean
FOREIGN KEY (`alart_id`) REFERENCES alart(`alart_id`)
instead of
FOREIGN KEY (`alart_id`) REFERENCES alart_types(`alart_id`)
Hope this makes sense.
In this table
CREATE TABLE alart_types (
alart_types_id BIGINT(20) unsigned NOT NULL AUTO_INCREMENT,
alarts_types_name varchar(45) NOT NULL,
PRIMARY KEY (alart_types_id)
) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=utf8;
it doesn't really make sense to have an autoincrement id number without also having a unique constraint on alarts_types_name. Without that unique constraint, you're almost certain to end up with a table whose data looks like this.
1 Warning
2 Critical
3 Warning
4 Warning
This constraint references a column that doesn't exist.
FOREIGN KEY (`alart_id`) REFERENCES alart_types(`alart_id`)
It should be
FOREIGN KEY (`alart_id`) REFERENCES alart_types(`alart_types_id`)