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

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)

Related

I cant add MySQL foreign key constraint

I have three tables user, department, and department_hod
user has a department_id, which is the primary key of department, also departement has hod which is the primary key of user.
But i am getting an error when adding the foreign key constraint of username in department_hod table,
Please help
--
-- Create a user table
--
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`username` varchar(50) NOT NULL,
`password` char(80) NOT NULL,
`emp_id` int(11) NOT NULL,
`designation` varchar(50) NOT NULL,
`department_id` int(11) NOT NULL,
`status` varchar(2) NOT NULL DEFAULT 'A',
`email_id` varchar(50) NOT NULL,
`account_status` varchar(2) NOT NULL DEFAULT 'U',
`validity_date` TIMESTAMP,
`deactivation_date` TIMESTAMP ,
`deactivated_by` varchar(50),
`deactivation_remarks` varchar(1000),
`creation_date` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
`updation_date` TIMESTAMP,
`created_by` varchar(50),
`updated_by` varchar(50),
CONSTRAINT `PK_USER_ID` PRIMARY KEY (`id`,`username`),
KEY `FK_DEPARTMENT_IDX_01` (`department_id`),
CONSTRAINT `FK_DEPARTMENT_ID_01` FOREIGN KEY (`department_id`)
REFERENCES `department` (`id`)
ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;
--
-- Create a department table
--
CREATE TABLE `department` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`status` varchar(2) NOT NULL DEFAULT 'A',
`creation_date` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
`updation_date` TIMESTAMP,
`created_by` varchar(50),
`updated_by` varchar(50),
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;
--
-- Add department_hod table
--
CREATE TABLE `department_hod` (
`department_id` int(11) NOT NULL,
`username` varchar(50) NOT NULL,
PRIMARY KEY (`username`,`department_id`),
KEY `FK_DEPARTMENT_idx_02` (`department_id`),
CONSTRAINT `FK_DEPARTMENT_id_02` FOREIGN KEY (`department_id`)
REFERENCES `department` (`id`)
ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `FK_USER_01` FOREIGN KEY (`username`)
REFERENCES `user` (`username`)
ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
SET FOREIGN_KEY_CHECKS = 1;
error is here
CONSTRAINT `FK_USER_01` FOREIGN KEY (`username`)
REFERENCES `user` (`username`)
ON DELETE NO ACTION ON UPDATE NO ACTION
Error is
Error Code: 1215. Cannot add foreign key constraint
Always provide complete error message. In a half of choices you may find the solution in it.
For your code the error message is
Failed to add the foreign key constraint. Missing index for constraint 'FK_USER_01' in the referenced table 'user'
So the problem can be fixed by absent index creation:
CREATE INDEX idx_user_username ON user (username);
https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=1f0fd24a8eb9cb5692b9d35dd1903045
can you please tell me that is it necessary to use index here? as it is only used for speeding up, do i have to use it beacuse of two primary keys in my user table? – shah-123
MySQL 8.0 Reference Manual / ... / FOREIGN KEY Constraints / Conditions and Restrictions
MySQL requires indexes on foreign keys and referenced keys so that foreign key checks can be fast and not require a table scan. In the referencing table, there must be an index where the foreign key columns are listed as the first columns in the same order. Such an index is created on the referencing table automatically if it does not exist. This index might be silently dropped later if you create another index that can be used to enforce the foreign key constraint. index_name, if given, is used as described previously.

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

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;

Cannot add or update a child row: a foreign key constraint fails mysql

CREATE TABLE `class` (
`class_id` int(11) NOT NULL AUTO_INCREMENT,
`section_name` varchar(50) NOT NULL,
`class_alias` varchar(200) NOT NULL,
`grading_scheme` int(11) NOT NULL DEFAULT '0',
`year` year(4) NOT NULL,
`grade_calc_method_id` varchar(20) DEFAULT NULL,
PRIMARY KEY (`class_id`)
) ENGINE=InnoDB AUTO_INCREMENT=48819 DEFAULT CHARSET=latin1;
CREATE TABLE `teachers` (
`teacher_id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`teacher_subject` varchar(20) NOT NULL DEFAULT 'None',
PRIMARY KEY (`teacher_id`),
KEY `user_id` (`user_id`,`school_id`)
) ENGINE=InnoDB AUTO_INCREMENT=48606 DEFAULT CHARSET=latin1;
CREATE TABLE `teacher_classes` (
`teacher_class_id` int(11) NOT NULL AUTO_INCREMENT,
`teacher_id` int(11) NOT NULL,
`class_id` int(11) NOT NULL,
PRIMARY KEY (`teacher_class_id`),
UNIQUE KEY `teacher_id_class_id` (`teacher_id`,`class_id`),
KEY `teacher_id` (`teacher_id`,`class_id`)
) ENGINE=InnoDB AUTO_INCREMENT=46707 DEFAULT CHARSET=latin1;
Trying to insure data consistency between the tables by using foreign key so that the DBMS can check for errors.I have another junction table teacher_classes
Here is my query to add foreign keys constraint
ALTER TABLE teacher_classes
ADD CONSTRAINT `tc_fk_class_id` FOREIGN KEY (`class_id`)
REFERENCES class (`class_id`) ON UPDATE NO ACTION ON DELETE NO ACTION,
ADD CONSTRAINT `tc_fk_teacher_id` FOREIGN KEY (`teacher_id`)
REFERENCES teachers (`teacher_id`) ON UPDATE NO ACTION ON DELETE NO ACTION;
've seen the other posts on this topic, but no luck, getting following error.
Cannot add or update a child row: a foreign key constraint fails
(DB_NAME.#sql-403_12, CONSTRAINT
tc_fk_teacher_id FOREIGN KEY (teacher_id) REFERENCES teachers
(teacher_id) ON DELETE NO ACTION ON UPDATE NO ACTION)
Too late to Answer. I just had the same problem the solution is easy.
You're getting this error because you're trying to or UPDATE a row to teacher_classes doesn't match the id in table teachers.
A simple solution is disable foreign key checks before performing any operation on the table.
SET FOREIGN_KEY_CHECKS = 0;
After you are done with the table enable it again.
SET FOREIGN_KEY_CHECKS = 1;
Or you can remove not null constraint and insert a NULL value in it.
That's most probably the column definition doesn't match properly. For table teachers the PK column definition is as below.
`teacher_id` int(11) NOT NULL AUTO_INCREMENT
Make sure you have the same definition in your child table teacher_classes

Foreign key constraint fails even when data types are the same

I'm building a table with a two part foreign key that references a two part key in another table. It isn't working, and I can't see why because the data types line up.
Can't create table 'tsugi.video_comments' (errno: 150)
Here's the code I'm trying to run:
CREATE TABLE `video_comments` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`video_id` varchar(11) NOT NULL DEFAULT '',
`link_id` int(11) NOT NULL,
`videoTime` int(11) NOT NULL,
`comment` text NOT NULL,
`parent` int(11) unsigned DEFAULT NULL,
`private` tinyint(1) DEFAULT NULL,
`replies` int(11) unsigned DEFAULT '0',
`reports` int(11) DEFAULT '0',
`user_id` int(11) NOT NULL,
`displayname` varchar(2048) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `video_ibfk_1` (`link_id`),
KEY `video_ibfk_2` (`user_id`),
CONSTRAINT `video_comments_ibfk_1` FOREIGN KEY (`parent`) REFERENCES `video_comments` (`id`) ON DELETE CASCADE,
CONSTRAINT `video_ibfk_1` FOREIGN KEY (`link_id`) REFERENCES `lti_link` (`link_id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `video_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `lti_user` (`user_id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `video_key` FOREIGN KEY (`link_id`, `video_id`) REFERENCES `video_ids` (`link_id`, `video_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=285 DEFAULT CHARSET=utf8;
The command runs successfully if I delete the last constraint, so that's where the problem is, not in the other constraints.
Here's the table it's referencing:
CREATE TABLE `video_ids` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`video_id` varchar(11) NOT NULL DEFAULT '',
`link_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `video_key` (`video_id`,`id`),
KEY `link_id` (`link_id`),
KEY `id` (`id`,`video_id`),
CONSTRAINT `video_ids_ibfk_1` FOREIGN KEY (`link_id`) REFERENCES `t_lti_link` (`link_id`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
To make sure that the video_id and link_id fields are exactly the same, I copied them directly from the existing table's code to the code for creating the new table. I expected that to solve it, but it did not. Here's the error log:
------------------------
LATEST FOREIGN KEY ERROR
------------------------
141114 22:04:09 Error in foreign key constraint of table tsugi/video_comments:
FOREIGN KEY (`link_id`, `video_id`) REFERENCES `video_ids` (`link_id`, `video_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=285 DEFAULT CHARSET=utf8:
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.5/en/innodb-foreign-key-constraints.html
for correct foreign key definition.
Foreign key references need to be to unique or primary keys. So, you can fix this just by having a unique declaration in video_ids:
CREATE TABLE `video_ids` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`video_id` varchar(11) NOT NULL DEFAULT '',
`link_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `video_key` (`video_id`,`id`),
KEY `link_id` (`link_id`),
KEY `id` (`id`,`video_id`),
UNIQUE (link_id, video_id),
CONSTRAINT `video_ids_ibfk_1` FOREIGN KEY (`link_id`) REFERENCES `t_lti_link` (`link_id`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
Here is a SQL Fiddle with an example.

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`)