I am using Mysql Workbench. I have already made the table.
Now I want to add foreign key in a table called Personal_Details that key is primary key in Login table.
But when I am trying to do so, it shows me the following error:
ERROR 1005: Can't create table 'shaadiDB.#sql-404_25' (errno: 121)
SQL Statement:
ALTER TABLE `shaadiDB`.`Personal_Details`
ADD CONSTRAINT `Login_Id`
FOREIGN KEY (`Login_Id` )
REFERENCES `shaadiDB`.`Login` (`Login_Id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION
, ADD INDEX `Login_Id` (`Login_Id` ASC)
It seems that the table Personal_Details is having data from which there might be some rows with Login_Id for which entry is not present in table Login.
If this is the case , then solution would be that you need to move the data to another table, then add constraint. After adding the constraint you need to add all rows back to table 1 by 1.
Error 121: This error explicitly is thrown when there is a duplication in key names.
Immediately after running your Alter ... statement, execute the following and observe the results.
SHOW ENGINE InnoDB STATUS;
Description text from the result will tell you on which key name the duplication is found.
Based on that you modify your ALTER ... statement and execute.
Alternatively you can also find if any such duplicate key name is defined by executing:
select constraint_name, constraint_type, table_name
from information_schema.table_constraints
where table_schema = DATABASE() -- and constraint_type = 'foreign key'
Constraint types can be anything like PRIMARY KEY, FOREIGN KEY, etc.
If you see any key names in the result that you are trying to use in your ALTER .. statement, you should modify them and execute.
before adding any constrain to a table that already have some data might cause this problem,try to add constrain with out data
Related
I am trying to rename an empty table with its old name.
I had created constraints in the past (innodb), but that table doesn't exist anymore and if I try to reuse its name (no matter if I create a new table or try to rename another table), I get the following error:
errno: 150 "Foreign key constraint is incorrectly formed"
LATEST FOREIGN KEY ERROR
------------------------
2021-07-16 14:50:24 0x2508 Error in foreign key constraint of table database/publisheremails:
there is no index in the table which would contain
the columns as the first columns, or the data types in the
table do not match the ones in the referenced table
or one of the ON ... SET NULL columns is declared NOT NULL. Constraint:
,
CONSTRAINT `publisheremails_ibfk_1` FOREIGN KEY (`agencyid`) REFERENCES `agencies` (`id`) ON UPDATE CASCADE
I tried to drop the constraint with this code:
ALTER TABLE old_publisheremails
DROP FOREIGN KEY publisheremails_ibfk_1;
I get the following error:
#1091 - Can't DROP FOREIGN KEY publisheremails_ibfk_1; check that it exists
I also tried to drop it with the old table name, but I get this error:
#1146 - Table 'database.publisheremails' doesn't exist
Same goes if I try to drop it from 'agencies'...
Check which foreign keys the table actually has and which name it has with
SELECT
TABLE_NAME,COLUMN_NAME,CONSTRAINT_NAME, REFERENCED_TABLE_NAME,REFERENCED_COLUMN_NAME
FROM
INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE
REFERENCED_TABLE_SCHEMA = '<database>' AND
REFERENCED_TABLE_NAME = 'old_publisheremails';
And you can't drop the publisheremails_ibfk_1 because it doesn't exist till now
So check the agencyid column if it has the same data type as agencies (id`) and change it
I'm getting a 1022 error regarding duplicate keys on create table command. Having looked at the query, I can't understand where the duplication is taking place. Can anyone else see it?
SQL query:
-- -----------------------------------------------------
-- Table `apptwo`.`usercircle`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `apptwo`.`usercircle` (
`idUserCircle` MEDIUMINT NOT NULL ,
`userId` MEDIUMINT NULL ,
`circleId` MEDIUMINT NULL ,
`authUser` BINARY NULL ,
`authOwner` BINARY NULL ,
`startDate` DATETIME NULL ,
`endDate` DATETIME NULL ,
PRIMARY KEY ( `idUserCircle` ) ,
INDEX `iduser_idx` ( `userId` ASC ) ,
INDEX `idcategory_idx` ( `circleId` ASC ) ,
CONSTRAINT `iduser` FOREIGN KEY ( `userId` ) REFERENCES `apptwo`.`user` (
`idUser`
) ON DELETE NO ACTION ON UPDATE NO ACTION ,
CONSTRAINT `idcategory` FOREIGN KEY ( `circleId` ) REFERENCES `apptwo`.`circle` (
`idCircle`
) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE = INNODB;
MySQL said: Documentation
#1022 - Can't write; duplicate key in table 'usercircle'
The most likely you already have a constraint with the name iduser or idcategory in your database. Just rename the constraints if so.
Constraints must be unique for the entire database, not just for the specific table you are creating/altering.
To find out where the constraints are currently in use you can use the following query:
SELECT `TABLE_SCHEMA`, `TABLE_NAME`
FROM `information_schema`.`KEY_COLUMN_USAGE`
WHERE `CONSTRAINT_NAME` IN ('iduser', 'idcategory');
Change the Foreign key name in MySQL. You can not have the same foreign key names in the database tables.
Check all your tables and all your foreign keys and avoid having two foreign keys with the same exact name.
From the two linksResolved Successfully and Naming Convention,
I easily solved this same problem which I faced. i.e., for the foreign key name, give as fk_colName_TableName. This naming convention is non-ambiguous and also makes every ForeignKey in your DB Model unique and you will never get this error.
Error 1022: Can't write; duplicate key in table
As others have mentioned, it's possible that the name for your constraint is already in use by another table in your DB. They must be unique across the database.
A good convention for naming foreign key constraints is:
fk_TableName_ColumnName
To investigate whether there's a possible clash, you can list all constraints used by your database with this query:
SELECT * FROM information_schema.table_constraints WHERE constraint_schema = 'YOUR_DB';
When I ran this query, I discovered I had previously made a temporary copy of a table and this copy was already using the constraint name I was attempting to use.
This can also arise in connection with a bug in certain versions of Percona Toolkit's online-schema-change tool. To mutate a large table, pt-osc first creates a duplicate table and copies all the records into it. Under some circumstances, some versions of pt-osc 2.2.x will try to give the constraints on the new table the same names as the constraints on the old table.
A fix was released in 2.3.0.
See https://bugs.launchpad.net/percona-toolkit/+bug/1498128 for more details.
I just spent the last 4 hours with the same issue. What I did was to simply make sure the constraints had unique names.
You can rename the constraints. I appended a number to mine so I could easily trace the number of occurrences.
Example
If a constraint in a table is named boy with a foreign key X
The next constraint with the foreign key X can be called boy1
I'm sure you'd figure out better names than I did. 🙂
I had this problem when creating a new table. It turns out the Foreign Key name I gave was already in use. Renaming the key fixed it.
You are probably trying to create a foreign key in some table which exists with the same name in previously existing tables.
Use the following format to name your foreign key
tablename_columnname_fk
I also encountered that problem.Check if database name already exist in Mysql,and rename the old one.
I'm trying to do a schema update using the app/console doctrine:schema:update --force command, but Doctrine fails on the following part:
An exception occurred while executing 'DROP INDEX IDX_E98F2859A074D5D7 ON contract':
SQLSTATE[HY000]: General error: 1553 Cannot drop index 'IDX_E98F2859A074D5D7': needed in a foreign key constraint
This is trivial to resolve according to another SO question. The table has:
KEY `IDX_E98F2859A074D5D7` (`some_table_id`),
CONSTRAINT `FK_E98F2859A074D5D7` FOREIGN KEY (`some_table_id`) REFERENCES `some_table` (`id`)
So this can be resolved manually by dropping the matching constraint. But is there a way to do it automatically?
If you use the information schema, you can easily construct the necessary ALTER TABLE commands; the relevant tables are here: SCHEMA KEY_COLUMN_USAGE and STATISTICS.
Following is an example for a query which generates the DDL statements:
SELECT CONCAT('ALTER TABLE ',kcu.TABLE_NAME,' DROP FOREIGN KEY ', kcu.CONSTRAINT_NAME,';') AS ddl
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu, INFORMATION_SCHEMA.STATISTICS stat
WHERE stat.table_schema = 'your_schema'
AND kcu.TABLE_NAME = stat.TABLE_NAME
AND kcu.COLUMN_NAME = stat.COLUMN_NAME
AND kcu.REFERENCED_TABLE_NAME IS NOT NULL
INTO OUTFILE '/tmp/ddl.sql';
And you can run it after reviewing it by running this statement:
SOURCE '/tmp/ddl.sql';
Above statement will look up constraint name and corresponding table name for every foreign key constraint, where an index exists on the same foreign key column in the same table. The result is stored in the file given by INTO OUTFILE.
Please review above statement carefully before running the generated ddl.
Problems with MySQL using InnoDB and dropping an unused, foreign key. The foreign key references another table's id. However, I don't need this field.
I've tried removing the fk index, which doesn't work - says it's needed in a foreign key contraint. And removing the field, which gives me an error:
1025 - Error on rename of './axis/#sql-ad8_1531' to './axis/Schedule' (errno: 150)
The table is currently empty. There are no tables referencing this field. Any ideas on how to get rid of this? Other than creating a new table?
If I'm reading the below error correctly, I can't drop the column since the fk index is declared. And I can't drop the index, because the column exists. Chicken & Egg??
LATEST FOREIGN KEY ERROR
111004 17:05:40 Error in foreign key constraint of table axis/Schedule:
there is no index in the table which would contain
the columns as the first columns, or the data types in the
table do not match the ones in the referenced table
or one of the ON ... SET NULL columns is declared NOT NULL. Constraint:
,
CONSTRAINT "fk_Schedule_Grp" FOREIGN KEY ("idGrp") REFERENCES "Grp" ("idGrp") ON DELETE NO ACTION ON UPDATE NO ACTION
InnoDB: Renaming table axis. to axis.Schedule failed!
You need to use
ALTER TABLE table_name DROP FOREIGN KEY constraint_name
Here constraint_name is the name of the constraint rather than the index. If you do not know what this is, you can find out by issuing a SHOW CREATE TABLE. It is the identifier that appears after the word CONSTRAINT.
Edit: From your addition to the question, it looks like you need to issue
ALTER TABLE table_name DROP FOREIGN KEY fk_Schedule_Grp
So I am trying to add a primary key to one of the tables in my database. Right now it has a primary key like this:
PRIMARY KEY (user_id, round_number)
Where user_id is a foreign key.
I am trying to change it to this:
PRIMARY KEY (user_id, round_number, created_at)
I am doing this in phpmyadmin by clicking on the primary key icon in the table structure view.
This is the error I get:
#1025 - Error on rename of './database/#sql-2e0f_1254ba7' to './database/table' (errno: 150)
It is a MySQL database with InnoDB table engine.
There is probably another table with a foreign key referencing the primary key you are trying to change.
To find out which table caused the error you can run SHOW ENGINE INNODB STATUS and then look at the LATEST FOREIGN KEY ERROR section.
As was said you need to remove the FKs before. On Mysql do it like this:
ALTER TABLE `table_name` DROP FOREIGN KEY `id_name_fk`;
ALTER TABLE `table_name` DROP INDEX `id_name_fk`;
For those who are getting to this question via google... this error can also happen if you try to rename a field that is acting as a foreign key.
To bypass this in PHPMyAdmin or with MySQL, first remove the foreign key constraint before renaming the attribute.
(For PHPMyAdmin users: To remove FK constrains in PHPMyAdmin, select the attribute then click "relation view" next to "print view" in the toolbar below the table structure)
If you are trying to delete a column which is a FOREIGN KEY, you must find the correct name which is not the column name. Eg: If I am trying to delete the server field in the Alarms table which is a foreign key to the servers table.
SHOW CREATE TABLE alarm;
Look for the CONSTRAINT `server_id_refs_id_34554433` FORIEGN KEY (`server_id`) REFERENCES `server` (`id`) line.
ALTER TABLE `alarm` DROP FOREIGN KEY `server_id_refs_id_34554433`;
ALTER TABLE `alarm` DROP `server_id`
This will delete the foreign key server from the Alarms table.
I had this problem, it is for foreign-key
Click on the Relation View (like the image below) then find name of the field you are going to remove it, and under the Foreign key constraint (INNODB) column, just put the select to nothing! Means no foreign-key
Hope that works!
If you are adding a foreign key and faced this error, it could be the value in the child table is not present in the parent table.
Let's say for the column to which the foreign key has to be added has all values set to 0 and the value is not available in the table you are referencing it.
You can set some value which is present in the parent table and then adding foreign key worked for me.