mysql alter table FOREIGN KEY! - mysql

(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'

Related

Use tuple as a foreign key

Let's say i have a table named borrows like this one:
CREATE TABLE IF NOT EXISTS `borrows`
( `memberID` int(11) NOT NULL ,
`ISBN` int(11) NOT NULL ,
`CopyNr` int(11) NOT NULL ,
`date_of_borrowing` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`date_of_reminder` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`memberID`,`ISBN`,`CopyNr`,`date_of_borrowing`) )
ENGINE=InnoDB DEFAULT CHARSET=latin1
I want this table to have (ISBN,CopyNr) as a foreign key to an other table named copies.What i tried is this:
ALTER TABLE `borrows` ADD FOREIGN KEY (`ISBN`,`copyNr`)
REFERENCES `copies`(`copyNr`) ON DELETE RESTRICT ON UPDATE RESTRICT;
This however gives me this error:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '(`ISBN`),(`copyNr`)) REFERENCES `copies`(`copyNr`) ON DELETE RESTRICT ON UPDATE ' at line 1
Should i create another column that would contain tuples of(ISBN,CopyNr) first?If yes,how can this happen?If not,how can i solve this?
UPDATE:This is the code for copies:
CREATE TABLE IF NOT EXISTS `copies`
( `copyNr` int(11) NOT NULL AUTO_INCREMENT,
`shelf` text NOT NULL,
`ISBN` int(11) NOT NULL,
PRIMARY KEY (`copyNr`,`ISBN`) )
ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1
ALTER TABLE `borrows` ADD FOREIGN KEY (`ISBN`,`copyNr`)
REFERENCES `copies`(`ISBN`,`copyNr`) ON DELETE RESTRICT ON UPDATE RESTRICT;
You should have composite index (ISBN, copyNr) on table copies

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

Error 1005 in MySQL upon execution of ALTER TABLE

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

Contraint sql error: #1005 - Can't create table

Error
I have a working site in one server. I decided to move it to another company. I exported the database with phpmyadmin and uploaded in the new server. Everytime I try to import the database I receive this error:
SQL query:
--
-- Constraints for table `seller_cart`
--
ALTER TABLE `seller_cart`
ADD CONSTRAINT `seller_cart_ibfk_1`
FOREIGN KEY ( `subscription` )
REFERENCES `subscription` ( `id` ) ,
ADD CONSTRAINT `seller_cart_ibfk_2`
FOREIGN KEY ( `user` )
REFERENCES `users` ( `user_id` )
ON DELETE CASCADE
ON UPDATE CASCADE ,
ADD CONSTRAINT `seller_cart_ibfk_3`
FOREIGN KEY ( `featured_item` )
REFERENCES `featured_item` ( `item` )
ON DELETE CASCADE
ON UPDATE CASCADE ;
MySQL said: Documentation
#1005 - Can't create table 'project123.#sql-12050_1d' (errno: 150) (Details...)
HERE'S THE STRUCTURE OF seller cart:
--
-- Table structure for table `seller_cart`
--
CREATE TABLE IF NOT EXISTS `seller_cart` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`user` bigint(20) NOT NULL,
`subscription` bigint(20) DEFAULT NULL,
`description` varchar(200) COLLATE utf8_unicode_ci DEFAULT NULL,
`item_listings` text COLLATE utf8_unicode_ci,
`featured_item` bigint(20) DEFAULT NULL,
`quantity` int(2) NOT NULL,
`price` float NOT NULL,
PRIMARY KEY (`id`),
KEY `user` (`user`),
KEY `subscription` (`subscription`),
KEY `featured_item` (`featured_item`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;
What could be the problem? I just exported and imported the samedatabase. Even tried on a localhost and the same problem.
This error is thrown when you are trying to refer a column which is not indexed.
Check if
subscription ( id )
users ( user_id )
featured_item ( item )
have valid indexes defined. If not, define them and run your ALTER ... statement.
Refer To: Rules for Foreign Key Constraints:
InnoDB and FOREIGN KEY Constraints

unable to create constraint in mysql table

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.