I seem to have run across a strange situation where there is a specific table name that I cannot use. Let me explain.
CREATE TABLE IF NOT EXISTS hotstick_work_orders (
work_order_id BIGINT UNSIGNED NOT NULL,
step_id TINYINT UNSIGNED NOT NULL,
user_id INT UNSIGNED NOT NULL,
FOREIGN KEY (work_order_id) REFERENCES work_orders (id) ON DELETE CASCADE ON UPDATE NO ACTION,
FOREIGN KEY (step_id) REFERENCES hotstick_steps (id) ON DELETE NO ACTION ON UPDATE NO ACTION,
FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE NO ACTION ON UPDATE NO ACTION,
PRIMARY KEY (work_order_id, step_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
This works fine on my local MySql stack (v5.6.17), but gives me error code #1005 when I try it using PhpMyAdmin (v4.0.10.7, MySQL v5.5.42) on GoDaddy.
Okay, you say, this is obviously just another case where the FK definitions don't match perfectly, or possibly one where a referenced table is missing an index on the column. However, I can't even create the table without FKs - the following fails just the same:
CREATE TABLE IF NOT EXISTS hotstick_work_orders (
work_order_id BIGINT UNSIGNED NOT NULL,
step_id TINYINT UNSIGNED NOT NULL,
user_id INT UNSIGNED NOT NULL,
PRIMARY KEY (work_order_id, step_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Even more interesting, if I run the original create table query but use a different name, even hotstick_work_order (without the final s), it works FINE. I can rename this table to anything I want (including longer names), EXCEPT for hotstick_work_orders. Trying gives me error #1025, but only with that specific name.
E.g.:
RENAME TABLE hotstick_work_order TO hotstick_work_orders;
Resulting Error: #1025 - Error on rename of './db/hotstick_work_order' to './db/hotstick_work_orders' (errno: -1)
# Whereas this works fine:
RENAME TABLE hotstick_work_order TO hotstick_work_orders_something;
I don't have any previous table with that name, nor could I find any existing constraints in the information_schema.table_constraints table.
Of course I can manage using a different table name, no big deal, but I'm very curious - what could possibly cause such behavior?
What you're probably suffering from is a bad case of cached naming. A proper server restart might solve your problem, but as you mentioned, you can't do it due to shared server configuration.
When I asked you to create a MyISAM table with the exact name was so that we could establish that the problem was indeed cached indexes or constraints linked to your table name. Now what I recommend you to do is:
Try and Repair the MyISAM table.
Try to Optimize the table.
Execute a SELECT SQL_NO_CACHE * FROM TABLE to stop MySQL from caching queries.
Drop the Table.
Re-create it as you wish it would be (with constraints and all, InnoDB).
Related
Continue to get this error in MariaDB 10.3.13/14/15/16 even though the table doesn't exist and the FK doesn't display in the system schema. I have read many of the posts regarding this error and am aware that the FK name cannot exist anywhere else in the DB, which it does not. This issue does not occur in 10.3.12, so I am beginning to wonder if this is a problem with MariaDB? I cannot believe the answer should be, "drop you database and start over", as there should be some way to get Maria to see that the FK does not exist.
Dropped the table completely and verified that the FK in question only exists in this table that was dropped.
I can get the table rebuilt by removing the declaration for the FK constraint from the create table statement and once the table rebuilds, the FK is there, like it somehow picked it up from still existing in the DB somewhere - crazy.
My create statement is shown below
CREATE TABLE `trace_properties` (
`MessageId` bigint(20) NOT NULL,
`PropertyName` varchar(255) NOT NULL,
`PropertyValue` varchar(4096) NOT NULL,
PRIMARY KEY (`MessageId`,`PropertyName`),
KEY `NameValueIDX` (`PropertyName`,`PropertyValue`(767)),
KEY `MessageIdIDX` (`MessageId`),
CONSTRAINT `FK_traceproperties_1` FOREIGN KEY (`MessageId`) REFERENCES `trace_messages` (`TraceMessageId`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
My expected results is that I should be able to drop trace_properties, which does happen successfully, and then perform a create using the script above, which fails 100% of the time indicating that the FK exists.
However, I can run the following query and get an empty result set, indicating that FK doesn't exist, at least in the information schema.
SELECT * FROM information_schema.TABLE_CONSTRAINTS
WHERE information_schema.TABLE_CONSTRAINTS.CONSTRAINT_TYPE = 'FOREIGN KEY'
AND information_schema.TABLE_CONSTRAINTS.TABLE_SCHEMA = 'idf';
I have this Query:
CREATE TABLE `team` (
`id` int(11) NOT NULL
);
/* SQL Error (1215): Cannot add foreign key constraint */
which clearly does not contain a foreign key declaration. So all answers I am finding online are not for me. The reason this error occurs must have been related to a MySQL caching issue. Because the table existed previously and I deleted it. Thus, renaming the table name in the create table command to teams creates the table just fine.
My question is, where does mysql store this cache and how can I delete it. In information_schema I cannot find it. in information_schema.INNODB_TABLES the table is no longer listed.
Update 1
Before deleting the table team it was created with foreign keys, with:
CREATE TABLE `team` (
`id` int(11) NOT NULL,
`name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`is_verified` tinyint(1) NOT NULL,
`uuid` char(36) COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '(DC2Type:guid)',
`foreign_uuid` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
ALTER TABLE `team`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `UNIQ_C4E0A61FD17F50A6` (`uuid`);
But now the error occurs with just the first (very simple) query.
Update 2
I tried
mysql> FLUSH LOGS;
mysql> RESET MASTER;
to no avail.
Update 3
After restarting the mysql service the error changed more concrete to:
CREATE TABLE `team` (
`id` int(11) NOT NULL
);
/* SQL Error (1822): Failed to add the foreign key constraint. Missing index for constraint 'FK_6C66F57B296CD8AE' in the referenced table 'team' */
When you are disabling foreign_key_checks, it allows you to all kind of things, especially
Setting foreign_key_checks to 0 also affects data definition statements: [...] DROP TABLE drops tables that have foreign keys that are referred to by other tables.
That's what you (or someone you can blame) did.
When you recreate the table, you need to make sure that the referenced constraints are technically valid (even if you keep foreign_key_checks disabled):
When re-creating a table that was dropped, an error is returned if the table definition does not conform to the foreign key constraints referencing the table.
The exact error you get depends a bit on what version you are using, for MySQL 5.5 it would be Error Code: 1005. Can't create table 'tablename' (errno: 150), since MySQL 5.6, the error message is
SQL Error (1215): Cannot add foreign key constraint
So the problem here is that another table is referencing your table with a foreign key constraint, but the new table definition doesn't fit.
A fairly easy way to find the culprit is to use show engine innodb status, it will contain, amongst other things, useful details in the LATEST FOREIGN KEY ERROR section, including the foreign key definition and the name of table. Alternatively, and especially if you suspect to have more than one foreign key problem, have a look at How do I see all foreign keys to a table or column? (which is where MySQL stores that information, although it's not a cache that you can clear).
While you can include the referenced column into your new table, it doesn't look as if you intend to honor that constraint anymore, so you probably need to drop the referencing foreign key (or table).
Topic
MariaDB InnoDB Foreign Key Issue
Want to start off by saying I'm new to InnoDB and spent all day reading posts yesterday I've tried multiple things along the way to get me where I am now so am I hosed or is there a way out of this dark forest.
I have a table that is central to a number of tables in my data model. So something along these lines:
create table users (id int not null auto_increment
, username varchar(255) NOT NULL
, password varchar(255) NOT NULL
, active int NOT NULL
, PRIMARY KEY (id))
ENGINE=InnoDB COLLATE=utf8_unicode_ci;
Decided to clean up some DELETE / UPDATE clauses on my FKs quickly this weekend...Famous Last Words...
A related table example is here
create table athing (id int not null auto_increment
, name varchar(255) not null
, status varchar(255) not null
, created_by_user_id int
, PRIMARY KEY (id)
, CONSTRAINT athing_fk1 FOREIGN KEY (created_by_user_id) REFERENCES users (id)
) ENGINE=InnoDB COLLATE=utf8_unicode_ci;
Problem
Modified the FK in the "ATHING" table to include ON DELETE SET NULL. Saved that modification everything seemed ok. I was using HeidiSQL to perform this.
Long story short I was trolling through my list of tables and low and behold my USERS table was GONE! Through a lot of reading and effort I was able to get things cleaned up but felt to really ensure things were good I dropped all FKs pointing at USERS table and dropped the table.
Now when I attempt to re-create the USERS table I receive this error:
ERROR 1005 (HY000): Can't create table `sprintdb`.`system_users` (errno: 150 "Foreign key constraint is incorrectly formed")
What I noticed post my first attempt at doing this is while I'd thought I'd dropped all FKs there were remnants of keys still out there specifically indexes that supported those keys on some of the tables. In querying the INNODB_SYS_TABLES and INNODB_SYS_INDEXES tables that those indexes that I thought were removed still exist in these system tables.
Is there a way to move beyond this I feel like there exists some piece of information somewhere whether it be in the file system or in the database itself that needs to be refreshed or removed so that I can move forward...thoughts?
I have received this message many times while using 3rd party tools to create tables and then constrain against existing tables. It's either one of two things:
The int columns have different sizes
The int columns have different flags (sans AUTO_INCREMENT)
As an example, I created a table with a tool that somehow created a column as INT(10) instead of the expected INT(11). Even though I just chose INT when creating both, it was messed up - never tracked down why.
Long story short, it's generally best to explicitly state the INT size when creating a table.
In your case, the following should work:
create table users (id int(11) not null auto_increment
, username varchar(255) NOT NULL
, password varchar(255) NOT NULL
, active int NOT NULL
, PRIMARY KEY (id))
ENGINE=InnoDB COLLATE=utf8_unicode_ci;
create table athing (id int(11) not null auto_increment
, name varchar(255) not null
, status varchar(255) not null
, created_by_user_id int(11) not null
, PRIMARY KEY (id)
, CONSTRAINT athing_fk1 FOREIGN KEY (created_by_user_id) REFERENCES users (id)
) ENGINE=InnoDB COLLATE=utf8_unicode_ci;
In my case, I received this error when my SQL script for creating the datastructure contained a foreign key that referenced a table that was not yet created. Moving the creating of the referencing table after creating the target table was the solution.
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 have a table like so:
CREATE TABLE `Words` (
`wordId` int(11) NOT NULL AUTO_INCREMENT,
... snip! ...
`PartOfSpeechpartOfSpeechId` int(11) DEFAULT NULL,
PRIMARY KEY (`wordId`) USING BTREE,
KEY `fk_Words_PartOfSpeech` (`PartOfSpeechpartOfSpeechId`),
CONSTRAINT `fk_Words_PartOfSpeech` FOREIGN KEY (`PartOfSpeechpartOfSpeechId`) REFERENCES `PartOfSpeech` (`partOfSpeechId`) ON DELETE SET NULL ON UPDATE NO ACTION,
) ENGINE=InnoDB AUTO_INCREMENT=7306 DEFAULT CHARSET=utf8
I need to convert the PartOfSpeechpartOfSpeechId column into an enumerated value (ie keep it as an INT column, but remove the table it references entirely).
Trying to drop the PartOfSpeech table fails as one would expect, due to the FK on Words. To fix this, I've run ALTER TABLE Words DROP FOREIGN KEY fk_Words_PartOfSpeech, using the name of the FK instead of the column as noted everywhere. I still get an error:
ERROR 1025 (HY000): Error on rename of './lexercise/#sql-1a5_263' to './lexercise/Words' (errno: 150)
On looking for the table Words, it has vanished. Gone. No idea where to. Presumably, MySQL's internal alter table code is creating a temp table and is failing to return it to its proper name/location.
What is going on here? How is it possible to lose a whole table on dropping a foreign key? My background is in Postgres, not sure how best to debug this.
OK, so for anyone who finds this at some point with the same issue, here's what I think was happening:
I had another foreign key on the table (not shown above) that referenced a table that had been renamed prior to trying to drop the FK above. I think that the presence of that FK was what was causing the error on my ALTER TABLE call.
MySQL basically rebuilds the table schema during ALTER TABLE calls - it does not make incremental changes. As a result, if you have other things wrong with the table schema, make sure you identify them and fix them as well if you're losing tables randomly.
Oh, and MySQL REALLY should handle this better. My god.