MySQL fails because of FK constraint that should not exist - mysql

I'm running the following very boring query:
alter table mytable change user_id user_id varchar(36) null default null,
add foreign key (user_id) references users(id) on delete set null;
But it fails with the following error:
#1452 - Cannot add or update a child row: a foreign key constraint fails
(`mydatabase`.`#sql-602_60f`, CONSTRAINT `#sql-602_60f_ibfk_4`
FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE SET NULL
The problem is that that foreign key constraint doesn't exist, so I can't delete it. There are 3 foreign key constaints on the table (mytable_ibfk_1, mytable_ibfk_2, mytable_ibfk_3), but nothing with the name mentioned, and trying to delete it produces another error.
Any ideas how to fix this?

As Michael Berkowski pointed out, I was misreading the error, which was pointing to conflicting values in the two columns, not to an existing phantom constraint that I couldn't delete.
The root of the problem was that the column had previously accepted empty string values (''), and those needed to be converted to NULL in order for the foreign key constraint to be put in place.

Related

MySql workbench: add Foreign key error

I am trying to add foreign key 'USERNAME' in tutorial table, but there was an error.
Executing:
ALTER TABLE `databse`.`tutorial`
ADD CONSTRAINT `USERNAME`
FOREIGN KEY (`USERNAME`)
REFERENCES `databse`.`register` (`USERNAME`)
ON DELETE CASCADE
ON UPDATE CASCADE;
Operation failed: There was an error while applying the SQL script to the database.
ERROR 1452: Cannot add or update a child row:
a foreign key constraint fails (`databse`.`#sql-e7c_5`, CONSTRAINT `USERNAME` FOREIGN KEY (`USERNAME`)
REFERENCES `register` (`USERNAME`) ON DELETE CASCADE ON UPDATE CASCADE)
SQL Statement:
ALTER TABLE `databse`.`tutorial`
ADD CONSTRAINT `USERNAME`
FOREIGN KEY (`USERNAME`)
REFERENCES `databse`.`register` (`USERNAME`)
ON DELETE CASCADE
ON UPDATE CASCADE
Foreign key setting:
Tutorial table setting:
Any ideas ? thank you
I solved it, i created a new 'tutorials' table replace 'tutorial' table, and use same way to add foreign key, it worked! = =
still thank you for your helps !!
as stated here :
A FOREIGN KEY is a field (or collection of fields) in one table that refers to the PRIMARY KEY in another table.
In the code you show : you try to reference the "USERNAME" column, wich is not a primary key in your last capture
So you can either change your primary key in the register table to USERNAME, or you can change the foreign key to reference TutorialName
You have two table one is child table and second is parent table .So you would need to guarantee that each child column has NULL or has values that present in parent column.
This problem is normally caused by mismatching of values presented in the two columns constrained by the new foreign key.
That is, the value presented in the child table does not have a reference presented in the parent table.
when creating a foreign key, you need to make sure that:
the table type supports foreign key
there is a index on the foreign key column
the types of data of the two columns constrained by a foreign key are similar enough so that they can be converted to each other
the data presented in both columns constrained by a foreign key is consistent.

Changing MYSQL server to match new rails application version KEY, CONSTRAINT, and COLUMN

SETTING
I have a rails application that references an external mysql server. I am about to push some changes to the rails application. I made some changes to my local/test version of the application's database using rails migrations, but my production/live version of the application's database is not on a server that has the rails application, so I don't think I can just run the rails migration on the mysql database.
QUESTION
How do I safely add the following column, key and constraint:
`item_id` int(11) DEFAULT NULL,
KEY `index_notifications_on_item_id` (`item_id`),
CONSTRAINT `fk_rails_f395ae520f` FOREIGN KEY (`item_id`) REFERENCES `items` (`id`) ON DELETE CASCADE,
and safely change the unique key:
UNIQUE KEY `item_id_and_user_id_stand_id_unique_index` (`item_id`,`user_id`,`stand_id`)
to
UNIQUE KEY `item_id_and_user_id_stand_id_notified_user_id_unique_index` (`item_id`,`user_id`,`stand_id`,`notified_user_id`),`)
ATTEMPTS
CONCERNING THE CONSTRAINT AND KEY
I try running:
ALTER TABLE notifications ADD FOREIGN KEY fk_rails_f395ae520f(item_id) REFERENCES items(id) ON DELETE CASCADE;
But, I run into 2 issues:
1: It names the key what I want the constraint to be named and makes up its own constraint name.
OUTPUT:
KEY `fk_rails_f395ae520f` (`item_id`),
CONSTRAINT `notifications_ibfk_2` FOREIGN KEY (`item_id`) REFERENCES `items` (`id`) ON DELETE CASCADE,
It requires me to temporarily set: set foreign_key_checks = 0; or else I get the error:
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (DB_NAME.#sql-3c9_49, CONSTRAINT #sql-3c9_49_ibfk_2 FOREIGN KEY (item_id) REFERENCES items (id) ON DELETE CASCADE)
and I do not know if doing that is "safe" to do on a production/live server.
CONCERNING THE COLUMN AND UNIQE KEY
I believe I have the column and unique keys safely added with:
ALTER TABLE notifications add COLUMN item_id INT(11) DEFAULT NULL;
ALTER TABLE notifications DROP INDEX index_notifications_on_user_id_and_notified_user_id, ADD UNIQUE KEY `item_id_and_user_id_stand_id_notified_user_id_unique_index` (stand_id, user_id, notified_user_id, item_id);
CLARIFICATION
The reason I bring up the column and unique key even though I may have it working is the same reason I gave a setting: I am new to this and may be taking a flawed approach to the whole scenario. I am hoping this context allows someone to call me out on it if that's the case.
UPDATE 1
ALTER TABLE notifications ADD CONSTRAINT fk_rails_f395ae520f FOREIGN KEY index_notifications_on_item_id(item_id) REFERENCES items(id) ON DELETE CASCADE;
outputs:
CONSTRAINT `fk_rails_f395ae520f` FOREIGN KEY (`item_id`) REFERENCES `items` (`id`) ON DELETE CASCADE,
Which is what I want, but I am still working on the KEY section.
UPDATE 2
ALTER TABLE notifications add COLUMN item_id INT(11) DEFAULT NULL;
ALTER TABLE notifications DROP INDEX index_notifications_on_user_id_and_notified_user_id, ADD UNIQUE KEY `item_id_and_user_id_stand_id_notified_user_id_unique_index` (stand_id, user_id, notified_user_id, item_id);
CREATE INDEX index_notifications_on_item_id ON notifications (item_id);
ALTER TABLE notifications ADD CONSTRAINT fk_rails_f395ae520f FOREIGN KEY index_notifications_on_item_id(item_id) REFERENCES items(id) ON DELETE CASCADE;
I believe these four lines in sequence answers the question of how to manually handle what my rails migration does. But, I am going to leave this question here. The question that remains is: "is it a terrible idea to do what I just did? and if so, how to do proceed?"

MySQL - foreign key constrained by primary key in same table, error #1452

I created a table where cat_parent_id is a foreign key is constrained by the primary key cat_id, using this:
CREATE TABLE categories (
cat_id SMALLINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
cat_parent_ID SMALLINT,
cat_name VARCHAR(40)
INDEX cat_id(cat_id),
FOREIGN KEY(cat_id) REFERENCES categories(cat_id),
);
When I try to insert a record where cat_parent_ID is NULL, I get the error:
#1452 - Cannot add or update a child row: a foreign key constraint fails (`myDatabase`.`categories`, CONSTRAINT `categories_ibfk_1` FOREIGN KEY (`cat_id`) REFERENCES `categories` (`cat_id`))
How can the foreign key constraint fail when there is no foreign key to begin with? Is the constraint only possible if null is not allowed?
I can only insert records successfully if I disable the constraint, which is not what I want. I need the parent_id to be optional, and if it has a value then it be an existing cat_id only
This will create a circular foreign key, which will prevent any insertion into the table.
FOREIGN KEY(cat_id) REFERENCES categories(cat_id),
EDIT: Perhaps you meant to put the PK on cat_parent_id?
You have one root record which doesn't have a parent. For this one, you must first disable foreign key constraints.
SET FOREIGN_KEY_CHECKS=0;
Insert the record.
Then don't forget to re-enble foreign key constraints
SET FOREIGN_KEY_CHECKS=1;
Then from now own, make sure your inserts include an existing parent.
How can the foreign key constraint fail when there is no foreign key
to begin with? Is the constraint only possible if null is not allowed?
If you want to add other records which do not have a FK value, make sure that NULL is allowed.

Error (150) Generated By An SQL Script?

I am trying to create a table on MySQL using an SQL script and the MySQL database keeps on giving me error 150. I've tried the following code in both Navicat and MySQL Workbench and both give an 150 error.
It appears that this is a foreign key problem but i cant actually see what the problem with my code is and was wondering if more expereinced DB users would have any inkling to the problem?
SET FOREIGN_KEY_CHECKS=0;
CREATE TABLE `network_invites` (
`invite_ID` int(11) NOT NULL AUTO_INCREMENT,
`invite_From` int(11) NOT NULL,
`invite_Network` int(11) NOT NULL,
`invite_NetCreator` int(11) NOT NULL,
`invite_Message` varchar(256) NOT NULL,
`invite_Date` date DEFAULT NULL,
PRIMARY KEY (`invite_ID`),
KEY `invite_From` (`invite_From`),
KEY `invite_Network` (`invite_Network`),
KEY `invite_NetCreator` (`invite_NetCreator`),
CONSTRAINT `network_invites_ibfk_1` FOREIGN KEY (`invite_From`) REFERENCES `users` (`user_ID`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `network_invites_ibfk_2` FOREIGN KEY (`invite_Network`) REFERENCES `networks` (`network_ID`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `network_invites_ibfk_3` FOREIGN KEY (`invite_NetCreator`) REFERENCES `networks` (`network_Creator`) ON DELETE CASCADE ON UPDATE CASCADE
)ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=latin1;
I cant see what the FK problem is, those fields do exist on the DB and they are of the same datatype.
Thanks for any help.
I think the workaround is :
create the table without constraints
add constraints using ALTER TABLE
again , this is a workaround , and would love to hear from people#mysql or someone more experienced
Make sure the 2 Table Types are both InnoDB. Also make sure your Primary and Foreign keys are all Unsigned.
All these settings can be changed in NaviCat using the "Design Table" option.
I've come across this problem many times, and this does the trick 99% of the time.
You need to have indexes on users.user_ID, networks.network_ID and networks.network_Creator and the types of the columns should be exactly the same as in the network_invites table.
The problem is a typo:
CONSTRAINT `network_invites_ibfk_2`
FOREIGN KEY (`invite_Network`)
REFERENCES `networks` (`network_ID`) ---<--- either here
ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `network_invites_ibfk_3`
FOREIGN KEY (`invite_NetCreator`)
REFERENCES `networks` (`network_Creator`) ---<--- or here (more probable)
ON DELETE CASCADE ON UPDATE CASCADE
Your networks table Primary Key is probably network_ID and not network_Creator.

error adding a foreign key constraint

I have the following query:
ALTER TABLE ROUTE ADD FOREIGN KEY (RID) REFERENCES RESERVATION(RID) ON DELETE CASCADE
but it generates me an error:
#1452 - Cannot add or update a child row: a foreign key constraint fails (`SmarTrek`.`#sql-91e_d09`, CONSTRAINT `FK_RID` FOREIGN KEY (`RID`) REFERENCES `RESERVATION` (`RID`) ON DELETE CASCADE)
In designer mode, here's what it looks like:
That would meant that you already have data in the ROUTE table that does not satisfy the foreign key constraint.
To find the offending records, so you can update them to some other value (that exists), you can use
select *
from route
where rid not in (select rid from reservation)
THERE may b 2 reasons
there may b some row in ROUTE TABLE which have RID that does not exist in RESERVATION(RID)
or check the DATATYPE OF ROUTE (RID) & RESERVATION(RID) both should be same ( unsigned/signed)