SQL Foreign Key Issue - mysql

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

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.

MySQL:ERROR 1215: Cannot add foreign key constraint

I've been trying to follow a tutorial that I've came across, which is about spring security. In some place, I need to create 2 tables in my database which is user and authorities. While doing this, I am using this script that is suggested like in the tutorial. http://docs.spring.io/spring-security/site/docs/3.0.x/reference/appendix-schema.html
I've already a user table in my db, so I just need to add autohirites table. Since I'm using MySQL, I've changed that query like below:
create table authorities (
username varchar(70) not null,
authority varchar(50) not null,
CONSTRAINT fk_authorities_users foreign key(username) references user(userFirstName));
create unique index ix_auth_username on authorities (username,authority);
Also, here is my user table too:
CREATE TABLE `user` (
`userId` INT(11) NOT NULL AUTO_INCREMENT,
`userFirstName` VARCHAR(70) NOT NULL,
`userLastName` VARCHAR(70) NOT NULL,
`userEmail` VARCHAR(70) NOT NULL,
`userAddress` VARCHAR(500) NULL DEFAULT NULL,
`userPhoneNumber` INT(13) NULL DEFAULT NULL,
`isActive` BINARY(50) NULL DEFAULT '1\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0',
`userPassword` VARCHAR(50) NOT NULL,
`userConfirmPassword` VARCHAR(50) NOT NULL,
PRIMARY KEY (`userId`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
AUTO_INCREMENT=2
;
When I try to run my first query which is going to create authorities table, I am getting ERROR 1215: Cannot add foreign key constraint error.
So far, I've been looked into these questions below, but none of them answered my problem + I think they are both the same questions:
MySQL Cannot Add Foreign Key Constraint
MySQL Error 1215: Cannot add foreign key constraint
Try making userFirstName column unique.
You haven't mentioned what the engine is for authorities, your user table does not have a unique index on userFirstName that would mean authoritiest would need to be INNODB. because:
InnoDB allows a foreign key constraint to reference a non-unique key.
This is an InnoDB extension to standard SQL.
But I don't recommend this at all, it's always best to have a foreign key referencing a PRIMARY KEY, where that's not possible another unique key.
What you should really do is change your table as follows:
CREATE TABLE authorities (
userid INT(11) not null,
authority varchar(50) not null,
CONSTRAINT fk_authorities_users foreign key(username) references user(userid));
create unique index ix_auth_username on authorities (username,authority));
By doing so you are referencing a PRIMARY KEY but more importantly reducing a great deal of redundancy from your tables. There is absolutely no point in having the same ~70 character field repeated in both tables.

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

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.

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'