Error 1005 in MySQL upon execution of ALTER TABLE - mysql

This is a long question please read through. I have listed some of the links I have referred, but I have read all the suggestion thrown up while posting this question. This is not a duplicate question as marked here https://stackoverflow.com/questions/31341481/unable-to-figure-out-the-cause-for-error-1005-in-mysql-database.
I've been trying to write a small MySQL database, which contains two tables role and user defined as follows:
role
CREATE TABLE `role` (
`roleid` varchar(20) NOT NULL,
`role_name` varchar(255) NOT NULL,
`permission` int(11) NOT NULL,
PRIMARY KEY (`roleid`),
UNIQUE KEY `roleid` (`roleid`),
UNIQUE KEY `role_name` (`role_name`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
user
CREATE TABLE `user` (
`uid` int(11) NOT NULL AUTO_INCREMENT,
`uname` varchar(255) NOT NULL,
`slug` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`rid` varchar(20) NOT NULL,
UNIQUE KEY `uid` (`uid`),
UNIQUE KEY `uname` (`uname`),
UNIQUE KEY `slug` (`slug`),
UNIQUE KEY `email` (`email`),
UNIQUE KEY `password` (`password`),
KEY `rid` (`rid`),
CONSTRAINT `user_ibfk_1` FOREIGN KEY (`rid`) REFERENCES `role` (`roleid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
So now when I issue the ALTER TABLE 'user' DROP FOREIGN KEY;
I get an error:
ERROR 1005 (HY000): Can't create table 'parth.#sql-418_24' (errno: 150)
parth is the name of the database.
I've consulted following discussions:
Error 1005 in MySQL
Error 1005 in MySQL (from foreign key syntax?)
Foreign Key in MySQL : ERROR 1005
Foreign key issue in mysql (error 1005)
Special Characters in MySQL Table Name
MySQL Reference https://dev.mysql.com/doc/refman/5.7/en/alter-table.html
The SHOW ENGINE INNODB STATUS gave the following output regarding the above situation:
------------------------
LATEST FOREIGN KEY ERROR
------------------------
150710 18:20:35 Error in foreign key constraint of table parth/#sql-418_24:
foreign key:
Syntax error close to:
Please help me figure this out. Thanks.
The table parth/#sql-418_24 generated automatically when I executed the ALTER TABLE command. According to the reference manual ALTER TABLE works by copying the contents of the original table into a temporary table, which in this case is #sql-418_24 which is then renamed to the name of the table as specified in the schema. So it doesn't seem like a problem with special characters in table name. Please help.
MySql Version 5.5.43-0ubuntu0.14.04.1
operating system Ubuntu 14.04
Thanks for helping.

try this ...
ALTER TABLE `user` DROP FOREIGN KEY `user_ibfk_1`;
you are supposed to drop a constraint, here the constraint is named user_ibfk_1

Related

Unable to create foreign key in database

I am trying to create a table with a varchar column as foreign key but MySQL gives me an error while creating the table. My query is like this:
CREATE TABLE `survey_hesco_subdivision` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`circle_code` VARCHAR(100) DEFAULT NULL,
`name` VARCHAR(100) DEFAULT NULL,
`circle_name` VARCHAR(100) DEFAULT NULL,
`division_code` VARCHAR(100) DEFAULT NULL,
`sub_div_code` VARCHAR(100) NOT NULL,
`division_name` VARCHAR(100) DEFAULT NULL,
PRIMARY KEY (`id`,`sub_div_code`),
KEY `id` (`id`)
) ENGINE=INNODB AUTO_INCREMENT=91 DEFAULT CHARSET=latin1;
The above table is already in used
Create table `accurate_mam`.`meter_ping`(
`id` int(11) NOT NULL AUTO_INCREMENT,
`meter_id` int(11) NOT NULL,
`meter_msn` varchar(100),
`sub_div_code` varchar(100) NOT NULL,
`sub_div_name` varchar(100),
primary key (`id`),
constraint `FK_PING_METER_ID` foreign key (`meter_id`) references
`accurate_mam`.`meters`(`id`) on delete Cascade,
constraint `FK_PIN_SUB_DIV` foreign key (`sub_div_code`) references
`accurate_mam`.`survey_hesco_subdivision`(`sub_div_code`) on delete Cascade
) ENGINE=InnoDB charset=latin1 collate=latin1_swedish_ci
The error I am getting is
Error Number : 1005
Error Message: Can't create table accurate_mam.meter_ping (errno: 150 "Foreign key constraint is incorrectly formed")
I have already looked into this question
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.
InnoDB permits a foreign key to reference any index column or group of
columns. However, in the referenced table, there must be an index
where the referenced columns are listed as the first columns in the
same order.
So, just create a index like this, before creating child table :
CREATE INDEX `idx_survey_hesco_subdivision_sub_div_code` ON survey_hesco_subdivision(sub_div_code);
Although, It is not best practice to use non-unique column as reference columns in relationship. DELETE CASCADE will not behave properly in that case. I will suggest you create a unique key on sub_div_code of primary table as well.
For more details, refere to this
Source : Cannot add foreign key - StackOverflow
Have you already run CREATE TABLE meters? There error is caused by that table being missing. Let's see that CREATE.

Duplicate Key issue after lost connection even thou constraint does not exist

I was doing a migration on laravel for all my DB's (several clients). All DB are the same structure and one of them lost connection and failed before completion. I tried to migrate again and I ran into an issue with a duplicate foreign key.
After looking at the constraints
SELECT * FROM information_schema.KEY_COLUMN_USAGE ke where constraint_name = 'rt_eqmtfixedcycle_excav_id_foreign'
SQL result for schema
All other databases successfully inserted 'rt_eqmtfixedcycle_excav_id_foreign' key. But the one that failed 'smv_Forestalleonera' database did not appear, but.
If I try to insert again:
use smv_forestalleonera;
alter table `rt_eqmtfixedcycle` add constraint `rt_eqmtfixedcycle_excav_id_foreign` foreign key (`excav_id`) references `rt_truck` (`id`) on delete restrict on update cascade
I get the following error:
12:33:45 alter table `rt_eqmtfixedcycle`
add constraint `rt_eqmtfixedcycle_excav_id_foreign`
foreign key (`excav_id`)
references `rt_truck` (`id`)
on delete restrict
on update cascade Error Code: 1005. Can't create table `smv_forestalleonera`.`#sql-7f4d_a8f7` (errno: 121 "Duplicate key on write or update") 0.234 sec
I'm using MariaDB 10.2.7.
I've already removed the table and restarted the engine without any results.
(from comment)
CREATE TABLE rt_eqmtfixedcycle (
id smallint(5) unsigned NOT NULL,
excav_id smallint(5) unsigned DEFAULT NULL,
locload_id int(10) unsigned DEFAULT NULL,
locdump_id int(10) unsigned DEFAULT NULL,
updated_at datetime DEFAULT NULL,
updated_by int(10) unsigned DEFAULT NULL,
KEY rt_eqmtfixedcycle_id_foreign (id),
CONSTRAINT rt_eqmtfixedcycle_id_foreign
FOREIGN KEY (id) REFERENCES rt_truck (id) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8

Can't Constrain Both Junction Table Columns

I have a juction table that contains two foreign keys (from Profiles and Districts tables), with both columns as a composite primary key.
`profID` int(11) NOT NULL,
`distID` varchar(8) NOT NULL,
PRIMARY KEY (`profID`,`distID`)
I'd like to constrain both columns, but MySql throws an error:
#1050 - Table './database_name/z#002dprof#002ddist' already exists
In troubleshooting the problem, I've tried creating another duplicate junction table from scratch, but I get the same error. Oddly, MySQL will allow me to constrain one column or the other, but not both columns. I'm stumped, since I have other (non-junction) tables that have constraints on more than one foriegn key column.
By the way, I'm using phpMyAdmin, and all tables are InnoDB with utf-8.
Any help would be appreciated.
ADDED: SHOW CREATE TABLE results
CREATE TABLE `Profiles` (
`profID` int(11) NOT NULL AUTO_INCREMENT,
`email` varchar(64) NOT NULL,
`stID` varchar(2) NOT NULL,
`zip` varchar(5) NOT NULL,
PRIMARY KEY (`profID`),
KEY `stID` (`stID`,`zip`),
KEY `email` (`email`)
) ENGINE=InnoDB AUTO_INCREMENT=52 DEFAULT CHARSET=utf8
CREATE TABLE `Districts` (
`distID` varchar(8) NOT NULL,
`stID` varchar(2) NOT NULL,
`abbrev` varchar(16) NOT NULL,
PRIMARY KEY (`distID`),
KEY `stID` (`stID`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8
CREATE TABLE `z-prof-dist` (
`profID` int(11) NOT NULL,
`distID` varchar(8) NOT NULL,
PRIMARY KEY (`profID`,`distID`),
KEY `distID` (`distID`),
KEY `profID` (`profID`),
CONSTRAINT `z-prof-dist_ibfk_1` FOREIGN KEY (`distID`) REFERENCES `Districts` (`distID`)
ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8
I think I found a fix. Rather than using the phpMyAdmin function for adding a constraint (where I kept getting the error message), I instead followed marekful's lead by using an SQL ALTER TABLE query (with a new constraint name) as such:
ALTER TABLE `z-prof-dist`
ADD CONSTRAINT `test1`
FOREIGN KEY (`profID`) REFERENCES `Profiles` (`profID`)
ON UPDATE CASCADE
I still don't understand the cause of the original error, but I can see that the newly added foreign key constraint is working perfectly.

SQL Foreign Key Issue

I'm getting an issue with MySQL for a seeming simple addition of a foreign key. I asked Google, but to no avail. Here goes:
Create first table with:
| users | CREATE TABLE `users` (
`username` varchar(32) NOT NULL DEFAULT '',
`firstname` varchar(128) DEFAULT NULL,
`lastname` varchar(128) DEFAULT NULL,
`password` varchar(32) DEFAULT NULL,
PRIMARY KEY (`username`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 |
Create second table with:
| contacts | CREATE TABLE `contacts` (
`username` varchar(32) DEFAULT NULL,
`name` varchar(128) DEFAULT NULL,
`phonenumber` varchar(32) DEFAULT NULL,
`address` varchar(128) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1 |
Now I need to add a foreign key which links 'contacts' with 'users'.
ALTER TABLE contacts ADD FOREIGN KEY (username) references USERS(username));
But I get this error:
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 1
The objective is obviously to ensure that all entries in 'contacts' have a corresponding 'username' entry in 'users'.
Environment: Ubuntu 11.04, MySQL 5.1.58
I must be making a stupid mistake somewhere. Suggestions welcome.
First, change the engine of these 2 table from MyISAM to InnoDB. MyISAM does not support FOREIGN KEY constraints:
ALTER TABLE users
ENGINE = InnoDB ;
ALTER TABLE contacts
ENGINE = InnoDB ;
Then add the FOREIGN KEY, removing the extra parenthesis. There are 2 ways to do this. With the code you had, that will automatically add an index (key) on column username:
ALTER TABLE contacts
ADD FOREIGN KEY (username)
REFERENCES users(username);
Or explictedly adding the Index (Key) yourself and the Foreign Key constraint (you also choose the names of the index and constraint yourself):
ALTER TABLE contacts
ADD KEY username_ie (username),
ADD CONSTRAINT users_contacts_fk
FOREIGN KEY (username)
REFERENCES users(username);
ALTER TABLE contacts ADD FOREIGN KEY (username) references USERS(username));
You have an extra parenthesis at end of the line.
should be
ALTER TABLE contacts ADD CONSTRAINT FOREIGN KEY (username) references USERS(username);

mysql alter table FOREIGN KEY!

(I using workbench) i have table questions with id, user_id, text and table users with fields id, name
I need to relate this 2 tables!
I write following:
ALTER TABLE `mydb_development`.`questions`
ADD CONSTRAINT fk_QueUsers_1
FOREIGN KEY (`user_id`)
REFERENCES `mydb_development`.`users`(`id`);
but i get:
ERROR 1046: No database selected
SQL Statement:
ALTER TABLE `questions`
ADD FOREIGN KEY (`user_id`) REFERENCES `users`(`id`)
ERROR: Error when running failback script. Details follow.
ERROR 1046: No database selected
SQL Statement:
CREATE TABLE `questions` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`user_id` int(11) unsigned NOT NULL,
`text` text NOT NULL,
`security_token` varchar(40) NOT NULL,
`created_at` datetime NOT NULL,
`updated_at` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=373 DEFAULT CHARSET=utf8
ERROR 1046: No database selected
SQL Statement:
ALTER TABLE `questions`
ADD FOREIGN KEY (`user_id`) REFERENCES `users`(`id`)
ERROR: Error when running failback script. Details follow.
.....................
EDIT:
I tried to do:
USE `mydb_development`;
ALTER TABLE `mydb_development`.`questions`
ADD CONSTRAINT `fk_QueUsers_1`
FOREIGN KEY (`user_id`)
REFERENCES `mydb_development`.`users`(`id`);
and i get error:
Error Code: 1005
Can't create table 'survey_development.#sql-4ad_45' (errno: 150)
DOnt understand:S
EDIT:
my user table:
DROP TABLE IF EXISTS `mydb_development`.`users`;
CREATE TABLE `mydb_development`.`users` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `email` (`email`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1;
This seems to be mysql bug:
Read http://forums.mysql.com/read.php?22,19755,19755
Try to index the 'user_id' and run the script again.
Try selecting your database to see if it makes any difference
USE `mydb_development`;
First of all you want to get rid of the ERROR 1046: No database selected errors.
To do this make sure that you either:
Select a database with USE mydb_development;
Modify the ALTER/CREATE statements to include the db. E.g. ALTER TABLE mydb_development.questions
enter:
use `mydb_development`;
change the constraint name 'user_id' to something else like 'fk_user_id'