Mysql FOREIGN KEY error 150 - mysql

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

Related

I am trying to add foreign key constraint and am unable to figure out why it isn't adding the constraint [duplicate]

I am creating 2 tables in my database:
DROP TABLE IF EXISTS `med_pharmacy`;
CREATE TABLE IF NOT EXISTS `med_pharmacy` (
`med_pharmacy_id` int(11) NOT NULL AUTO_INCREMENT,
`med_id` int(11) NOT NULL,
`med_barcode` varchar(45) DEFAULT NULL,
`med_received` date DEFAULT NULL,
`med_expiry` date DEFAULT NULL,
`med_tablet` int(11) DEFAULT NULL,
`med_pill` int(11) DEFAULT NULL,
`clinic_id` varchar(45) DEFAULT NULL,
PRIMARY KEY (`med_pharmacy_id`),
KEY `fk_med_pharmacy_medication1_idx` (`med_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1261 DEFAULT CHARSET=utf8mb4;
AND:
DROP TABLE IF EXISTS `medication`;
CREATE TABLE `medication` (
`med_id` int(11) NOT NULL,
`med_name` varchar(75) NOT NULL,
`med_date_added` date DEFAULT NULL,
`clinic_id` varchar(45) DEFAULT NULL,
`med_type` varchar(15) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
And when I run the queries in wamp I got this error:
SQL query:
ALTER TABLE `med_pharmacy`
ADD CONSTRAINT `fk_med_pharmacy_medication1`
FOREIGN KEY (`med_id`)
REFERENCES
`medication` (`med_id`) ON DELETE CASCADE ON UPDATE CASCADE MySQL
said: Documentation
#1822 - Failed to add the foreign key constaint. Missing index for constraint 'fk_med_pharmacy_medication1' in the referenced table
'medication'
The tables already exists but I changed one field.
The column referenced in a foreign key must be indexed. You need to add an index on medication.med_id. In fact, this should probably be the primary key of the table.
ALTER TABLE medication ADD PRIMARY KEY (med_id);
if you are giving
ADD CONSTRAINT `fk_med_pharmacy_medication1`
FOREIGN KEY (`med_id`)
A FOREIGN KEY constraint does not have to be linked only to a PRIMARY KEY constraint in another table; it can also be defined to reference the columns of a UNIQUE constraint in another table.
so med_id should have primary key in medication or reference the columns of a UNIQUE constraint

MySQL composite unique key and foreign key bug

It seems that adding composite unique key with foreign keys included breaks the table: unable to drop unique key:
drop index test_unq on order_test
Error:
Cannot drop index 'test_unq': needed in a foreign key constraint
Steps to reproduce:
create table product_test (
id bigint unsigned not null auto_increment primary key
);
create table order_test (
id bigint unsigned not null auto_increment primary key,
product_id bigint unsigned not null,
foreign key (product_id) references product_test(id)
);
alter table order_test add some_field int not null;
alter table order_test add unique test_unq(product_id, some_field);
Running
SHOW CREATE TABLE order_test
returns
CREATE TABLE `order_test` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`product_id` bigint(20) unsigned NOT NULL,
`some_field` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `test_unq` (`product_id`,`some_field`),
CONSTRAINT `order_test_ibfk_1` FOREIGN KEY (`product_id`) REFERENCES
`product_test` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
Result looks invalid, there is a constraint but no key for product_id.
Any ideas how to recover table without dropping and creating it again?
Thanks!
EDIT:
Removing all other foreign keys does not help! Structure after removing:
CREATE TABLE `order_test` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`product_id` bigint(20) unsigned NOT NULL,
`some_field` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `test_unq` (`product_id`,`some_field`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
Same error when I try to drop index.
drop index test_unq on order_test
Error:
Cannot drop index 'test_unq': needed in a foreign key constraint

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

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)