I am getting an error trying to create table in phpmyadmin - mysql

I am trying to run the following:
CREATE TABLE IF NOT EXISTS table_name (
user_id int(11) NOT NULL,
other_id int(11) NOT NULL,
FOREIGN KEY (user_id) REFERENCES users(id),
FOREIGN KEY (other_id) REFERENCES other_table(id),
PRIMARY KEY (user_id, other_id)
);
and getting the following error:
#1005 - Can't create table 'database_name.table_name' (errno: 150)
am I doing something wrong? This works fine just running it in another environment rather than phpmyadmin sql environment.

Take a look at this SO question.
Note the correct answer. Check column types They need to match. May be your problem.
In general, Here is the authoritative guide to FK in Mysql.
In addition to SHOW ERRORS, in the event of a foreign key error
involving InnoDB tables (usually Error 150 in the MySQL Server), you
can obtain a detailed explanation of the most recent InnoDB foreign
key error by checking the output of SHOW ENGINE INNODB STATUS.
EDIT: Incorporating comments
Table on PHPMyAdmin were defaulting to MyISAM. On Local they were defaulting to to InnoDB. MyISAM does not support FK. This does not fully explain the difference, as based on MySql Documentation, It should just work, without creating the FK's. ( Perhaps a settings issue or Older Version Issue)

Does users and other_table exist?
You can't have the foreign key references to non-existant tables.
You can add the references afterwards with alter table.

DROP TABLE IF EXISTS `table_name`;
CREATE TABLE IF NOT EXISTS table_name (
user_id int(11) NOT NULL,
other_id int(11) NOT NULL,
FOREIGN KEY (user_id) REFERENCES users(id),
FOREIGN KEY (other_id) REFERENCES other_table(id),
PRIMARY KEY (user_id, other_id)
);

Related

Error "Cannot add foreign key constraint" without trying to create a foreign key

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

Unable to add two foreign keys to a table

I have two tables as follow:
1st Table:
CREATE TABLE User (
User_ID VARCHAR(8)NOT NULL PRIMARY KEY,
User_Name VARCHAR (25) NOT NULL,
User_Gender CHAR (1) NOT NULL,
User_Position VARCHAR (10) NOT NULL,
);
2nd table:
CREATE TABLE Training (
Training_Code VARCHAR(8) NOT NULL Primary Key,
Training_Title VARCHAR(30) NOT NULL,
);
I am trying to create a table which has two foreign keys to join both of the previous tables:
CREATE TABLE Request (
User_ID VARCHAR(8) NOT NULL,
Training_Code VARCHAR(8) NOT NULL,
Request_Status INT(1) NOT NULL
);
When I am trying to set the foreign keys in the new table, the User_ID can be done successfully but the Training_Code cannot be set to foreign key due to the error:
ERROR 1215 (HY000): Cannot add foreign key constraint
As I searched for this problem, the reason for it, is that data type is not the same, or name is not the same.. but in my situation both are correct so could you tell me what is wrong here ?
You need an index for this column in table Request too:
Issue first
CREATE INDEX idx_training_code ON Request (Training_Code);
Then you should be successful creating the foreign key constraint with
ALTER TABLE Request
ADD CONSTRAINT FOREIGN KEY idx_training_code (Training_Code)
REFERENCES Training(Training_Code);
It worked for me. But I've got to say that it worked without create index too, as the documentation of Using FOREIGN KEY Constraints states:
MySQL requires indexes on foreign keys and referenced keys so that
foreign key checks can be fast and not require a table scan. In the
referencing table, there must be an index where the foreign key
columns are listed as the first columns in the same order. Such an
index is created on the referencing table automatically if it does not
exist. This index might be silently dropped later, if you create
another index that can be used to enforce the foreign key constraint.
index_name, if given, is used as described previously.
Emphasis by me. I don't know what's the issue in your case.
Demo
Explanation of the issue
The behavior mentioned in the question can be reproduced if the table Training is using the MyISAM storage engine. Then creating a foreign key referencing the table Training will produce the mentioned error.
If there's data in the table, then simple dropping of the table would not be the best solution. You can change the storage engine to InnoDB with
ALTER TABLE Training Engine=InnoDB;
Now you can successfully add the foreign key constraint.

MySQL error code 1005 Can't create table (errno150) - (again) - in all the foreign keys

Background:
Yesterday I was creating a small database for practice, and created about 9 tables, and got this error in the create table statement of only one of them. The question about that is located here. Thankfully somebody told an alternative way by creating the table without the foreign key and then use the alter table statement to add the foreign key constraint, and it worked.
Today I am creating another database, and I am getting this error in all the tables which contain foreign keys. I have tried the alternative way of creating the table and then adding foreign keys by alter table statement. But it doesn't seem to help.
My Research:
I know this question has been been addressed before on this website, but I have tried the solutions on this, this page, except adding indexes because firstly, I don't need them in such a small database (second point in the first answer), and secondly I don't know them and I want to keep it simple. None of those answers helped.
Moreover, as it is mentioned here, " If the error message refers to error 150, table creation failed because a foreign key constraint was not correctly formed. "
Please tell me what's wrong with my foreign key constraint.
CREATE TABLE table1 (
table1_id INT(11) AUTO_INCREMENT,
name VARCHAR(5000),
code VARCHAR(5000),
color VARCHAR(5000),
PRIMARY KEY (table1_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE table2( -- error code 1005 can t create table errno 150 mysql
table2_id INT(11) AUTO_INCREMENT,
date DATE,
start_time TIME,
end_time TIME,
table1_id INT(11) COMMENT 'FK FROM table1',
PRIMARY KEY (table2_id),
FOREIGN KEY (table1_id)
REFERENCES table1(table1_id)
ON UPDATE CASCADE ON DELETE RESTRICT
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
So any hints/tips on this?

Error 1022 - Can't write; duplicate key in table

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.

MySQL Create table with indexes error

Ok, so I am creating tables in MySQL with indexes and foreign keys. I use MySQL Workbench to create the tables and then have it forward engineer a SQL create script (I do better in a visual DB environment than just writing out the SQL code by hand right away).
The problem is many times when I import the sql script into mysql, I get the classic eror:
#1005 - Can't create table 'db.tablename' (errno: 121)
I've managed to figure out the problem each time, usually index/foreign key related, but now I'm starting to get irritated at having to fix it each time. I don't really understand what the problem is (especially when a MySQL product is creating sql code for its own database). Below is some code that typically causes the problem.
CREATE TABLE IF NOT EXISTS `db`.`groupMembers` (
`groupMembersID` INT NOT NULL AUTO_INCREMENT ,
`groupID` INT NOT NULL ,
`userID` INT NULL ,
PRIMARY KEY (`groupMembersID`) ,
INDEX `group` (`groupID` ASC) ,
INDEX `user` (`userID` ASC) ,
CONSTRAINT `group`
FOREIGN KEY (`groupID` )
REFERENCES `db`.`groups` (`groupsID` )
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT `user`
FOREIGN KEY (`userID` )
REFERENCES `db`.`users` (`usersID` )
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;
The error usually comes from the first INDEX definition - even when I take out the index definition, I just get the error at the the first foreign key constraint definition. I've checked, and the foreign key remote column and the local column are the same data-type and size.
"errno 121 means a duplicate key error"
Constraints must have an unique name in the database, you might wanna change your FK names. Like so, FK_groupMembers_group and FK_groupMembers_user.