unable to create constraint in mysql table - mysql

I've got following tables:
node_sharing | CREATE TABLE `node_sharing` (
`user_id` int(11) NOT NULL,
`node_id` int(11) NOT NULL,
PRIMARY KEY (`user_id`,`node_id`),
KEY `fk_user_id_idx` (`user_id`),
KEY `fk_node_id_idx` (`node_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
and
users | CREATE TABLE `users` (
`id` int(11) NOT NULL,
`has_ard_access` tinyint(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
I would like to create following foreign key with a constraint:
ALTER TABLE `node_sharing`
ADD CONSTRAINT `fk_user_id`
FOREIGN KEY (`user_id` )
REFERENCES `users` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION;
and MySQL returns the following error:
ERROR 1005 (HY000): Can't create table 'MY_TABLE_NAME.#sql-4d0_218' (errno: 121)
What is wrong here?
PS node_sharing has been truncated, so there are no existing records that could disable putting the constraint on.

It is a duplicate key error. Did you have a table with same name before? If so, check InnoDB internal data dictionary. If not, check if you have another constraint with same name. Constraint names should be unique.

Related

MySQL Cluster - Composite foreign key error: Missing index for constraint

I want to add composite foreign key to my MySQL Cluster table. When I try locally the statement is executed, but on cluster I get the following error:
Failed to add the foreign key constraint. Missing index for constraint... in the referenced table 'y'
This is the statement:
ALTER TABLE x
ADD CONSTRAINT fk_x_y
FOREIGN KEY (y_id, tenant_id)
REFERENCES y(id, tenant_id);
I have executed SHOW FULL COLUMNS FROM for both tables and both columns in each table are the same. Also I have index in y table on id, tenant_id.
MySQL Cluster version: 8.0.25-cluster
Edit 1:
SHOW CREATE TABLE results:
Table x:
CREATE TABLE `x` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`tenant_id` bigint(20) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `fk_y_id_tenant_id` (`tenant_id`),
CONSTRAINT `fk_x_tenant_id` FOREIGN KEY (`tenant_id`) REFERENCES `tenant` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=ndbcluster AUTO_INCREMENT=446 DEFAULT CHARSET=utf8;
Table y:
CREATE TABLE `reference_list` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`tenant_id` bigint(20) NOT NULL,
PRIMARY KEY (`id`),
KEY `y_id_tenant_id` (`id`,`tenant_id`),
KEY `fk_y_id_tenant_id` (`tenant_id`),
CONSTRAINT `fk_y_id_tenant_id` FOREIGN KEY (`tenant_id`) REFERENCES `tenant` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=ndbcluster AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;
I am aware that tenant_id is DEFAULT NULL in one table and NOT_NULL in other, but changing both to DEFAULT NULL didn't solve the problem.
After running: SHOW WARNINGS; I found out I had to add UNIQUE index on id, tenant_id columns.

MySQL Error Number: 1452 (unusual case)

I tried adding a Foreign Key using this query:
ALTER TABLE `StripeBilling`
ADD CONSTRAINT `StripeBillingPatientRef`
FOREIGN KEY (PatientRef)
REFERENCES `Patient`(`PatientId`)
ON DELETE SET NULL;
My tables mysql_dump is:
CREATE TABLE IF NOT EXISTS `StripeBilling` (
...
`PatientRef` int(10) unsigned DEFAULT NULL,
...
) ENGINE=InnoDB AUTO_INCREMENT=10000000 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
ALTER TABLE `StripeBilling`
ADD PRIMARY KEY (`StripeBillingId`), ADD KEY `StripeBillingAgentRef` (`AgentRef`), ADD KEY `PatientRef` (`PatientRef`);
ALTER TABLE `StripeBilling`
MODIFY `StripeBillingId` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=10000000;
ALTER TABLE `StripeBilling`
ADD CONSTRAINT `StripeBillingAgentRef` FOREIGN KEY (`AgentRef`) REFERENCES `Agent` (`AgentId`) ON DELETE SET NULL;
And patient's table is:
CREATE TABLE IF NOT EXISTS `Patient` (
`PatientId` int(10) unsigned NOT NULL,
...
) ENGINE=InnoDB AUTO_INCREMENT=10000000 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
ALTER TABLE `Patient`
ADD PRIMARY KEY (`PatientId`), ADD UNIQUE KEY `PatientSerial` (`PatientSerial`);
ALTER TABLE `Patient`
MODIFY `PatientId` int(10) unsigned NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=10000000;
But MySQL returns an error:
Cannot add or update a child row: a foreign key constraint fails
(newportal_enc.#sql-3863_9f, CONSTRAINT StripeBillingPatientRef
FOREIGN KEY (PatientRef) REFERENCES Patient (PatientId) ON
DELETE SET NULL)
I'm confused because table newportal_enc.#sql-3863_9f does not exist in my database.
This is not due to the presence of the PatientRef index, becouse after removing of this index my issue still exists.
Why am I getting this error and how can I solve it?

Simple many-to-many sql relation

I'm trying to build the simplest MySQL db with two tables - users and many-to-many related table for friends.
So here's my initial SQL :
/*
Source Server Type : MySQL
Source Server Version : 50614
Target Server Type : MySQL
Target Server Version : 50614
File Encoding : utf-8
*/
SET NAMES utf8;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for `users`
-- ----------------------------
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) COLLATE utf8_polish_ci NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id_idx` (`name`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci;
SET FOREIGN_KEY_CHECKS = 1;
and now when trying to create the second table :
DROP TABLE IF EXISTS `friends`;
CREATE TABLE `friends` (
`user_id` int(10) unsigned NOT NULL,
`friend_id` int(10) unsigned NOT NULL,
PRIMARY KEY (`user_id`,`friend_id`),
KEY `FK_FRIENDS_2` (`friend_id`),
CONSTRAINT `FK_FRIENDS_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`),
CONSTRAINT `FK_FRIENDS_2` FOREIGN KEY (`friend_id`) REFERENCES `users` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
I'm getting the following error in Inno log :
------------------------
LATEST FOREIGN KEY ERROR
------------------------
2014-07-15 02:10:36 1341ab000 Error in foreign key constraint of table pc/friends:
FOREIGN KEY (`user_id`) REFERENCES `users` (`id`),
CONSTRAINT `FK_FRIENDS_2` FOREIGN KEY (`friend_id`) REFERENCES `users` (`id`)
) ENGINE=InnoDB 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.6/en/innodb-foreign-key-constraints.html
for correct foreign key definition.
How do I need to set the indexes to make this work ?
You have given your constraints names, which is unnecessary. You could just remove the names or rename one of the FK_FRIENDS_2 constraints. However, I like the more compact syntax:
CREATE TABLE `friends` (
`user_id` int(10) unsigned NOT NULL REFERENCES `users` (`id`),
`friend_id` int(10) unsigned NOT NULL REFERENCES `users` (`id`),
PRIMARY KEY (`user_id`, `friend_id`),
KEY (`friend_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
The fact that the name of a key and a foreign key constraint might conflict may seem confusing. In fact, just think of keys and constraints as being different types of the same thing.

MySQL Error : #1005 - Can't create table (errno: 150) When I try create more than 1 FK

I have this table:
CREATE TABLE IF NOT EXISTS `produtos` (
`id` int(11) NOT NULL auto_increment,
`idcatprodutos` int(11) NOT NULL,
`idcategoria` int(11) NOT NULL,
`idmarca` int(11) NOT NULL,
`nome` varchar(100) NOT NULL,
PRIMARY KEY (`id`),
KEY `FK_produtos_2` (`idcatprodutos`),
KEY `FK_produtos_3` (`idmarca`),
KEY `FK_produtos_4` (`idcategoria`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 ROW_FORMAT=DYNAMIC AUTO_INCREMENT=39 ;
and this table:
CREATE TABLE IF NOT EXISTS `sugestoes` (
`id` int(11) NOT NULL auto_increment,
`idproduto` int(11) NOT NULL,
`idsugestao1` int(11) NOT NULL,
`idsugestao2` int(11) NOT NULL,
`idsugestao3` int(11) NOT NULL,
`idsugestao4` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `FK_sugestoes_prod` (`idproduto`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 ROW_FORMAT=FIXED AUTO_INCREMENT=9 ;
I already have created a fk sugestoes.idproduto -> produtos.id working, but I want each of the other fields also refer to the produtos.id through new FK.
Run this command below that return MySQL Error : #1005 - Can't create table (errno: 150):
ALTER TABLE `infantile`.`sugestoes` ADD CONSTRAINT `FK_sugestoes_2` FOREIGN KEY `FK_sugestoes_2` (`idsugestao1`)
REFERENCES `produtos` (`id`)
ON DELETE SET NULL
ON UPDATE CASCADE
, ROW_FORMAT = FIXED;
Does anyone have any idea what's going on?
Try this,
it works:
ALTER TABLE `sugestoes`
ADD CONSTRAINT `FK_idproduto_produtos_1` FOREIGN KEY (`idproduto`) REFERENCES `produtos` (`id`),
ADD CONSTRAINT `FK_sugestoes_produtos_2` FOREIGN KEY (`idsugestao1`) REFERENCES `produtos` (`id`),
ADD CONSTRAINT `FK_sugestoes_produtos_3` FOREIGN KEY (`idsugestao2`) REFERENCES `produtos` (`id`),
ADD CONSTRAINT `FK_sugestoes_produtos_4` FOREIGN KEY (`idsugestao3`) REFERENCES `produtos` (`id`),
ADD CONSTRAINT `FK_sugestoes_produtos_5` FOREIGN KEY (`idsugestao4`) REFERENCES `produtos` (`id`)
UPDATE:
You can not specify
ON DELETE SET NULL
Because of this:
You have defined a SET NULL condition though some of the
columns are defined as NOT NULL
You can see exact error when you run
SHOW ENGINE INNODB STATUS;
Perhaps removing the ROW_FORMAT = FIXED:
ALTER TABLE `infantile`.`sugestoes`
ADD CONSTRAINT `FK_sugestoes_2`
FOREIGN KEY `FK_sugestoes_2` (`idsugestao1`)
REFERENCES `produtos` (`id`)
ON DELETE SET NULL
ON UPDATE CASCADE
;
On second thought, how do you expect the ON DELETE SET NULL to behave when your column is defined with NOT NULL ?
And third, does the table has any data in it? If some of the rows violate this FK constraint, then you can't create that FK.

How to update foreign key value in mysql database

I have three tables: categories, languages and categories_languages. Categories_languages is many to many table which links together categories and languages. I would like to update a foregin key value in table languages but it throws me error #1451 - Cannot delete or update a parent row: a foreign key constraint fails!
CREATE TABLE IF NOT EXISTS `categories` (
`id` int(11) unsigned NOT NULL auto_increment,
`name` varchar(20) NOT NULL,
`modified` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `languages` (
`id` char(2) NOT NULL,
`name` varchar(20) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `categories_languages` (
`id` int(11) unsigned NOT NULL auto_increment,
`category_id` int(11) unsigned NOT NULL,
`language_id` char(2) NOT NULL,
`translation` varchar(20) NOT NULL,
PRIMARY KEY (`id`),
KEY `fk_category_id_language_id` (`category_id`,`language_id`),
KEY `fk_language_id` (`language_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ;
ALTER TABLE `categories_languages`
ADD CONSTRAINT `categories_languages_ibfk_1` FOREIGN KEY (`category_id`) REFERENCES `categories` (`id`) ON DELETE CASCADE,
ADD CONSTRAINT `categories_languages_ibfk_2` FOREIGN KEY (`language_id`) REFERENCES `languages` (`id`) ON DELETE CASCADE;
The error is clear to me, but how can I update a key value in this case? I tried adding ON UPDATA CASCADE:
ALTER TABLE `categories_languages`
ADD CONSTRAINT `categories_languages_ibfk_1` FOREIGN KEY (`category_id`) REFERENCES `categories` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `categories_languages_ibfk_2` FOREIGN KEY (`language_id`) REFERENCES `languages` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
but that also fails with message: MySQL said: Documentation #1005 - Can't create table './db_dodo/#sql-c2f_80e6f.frm' (errno: 121)
You can temporarily suspend foreign key checking:
SET foreign_key_checks = 0;
UPDATE languages SET id='xyz' WHERE id='abc';
UPDATE categories_languages SET language_id='xyz' WHERE language_id='abc';
SET foreign_key_checks = 1;
EDIT: As for the foreign key problem: is the data stored on a local or a remote file system? errno 121 is EREMOTEIO (Remote I/O error). Perhaps there are permission problems on the target file system or it doesn't support the # character in filenames?
If you are looking for a temp solution you can also change the ON UPDATE action to CASCADE and modify your ids