MySQL MariaDB wont create Table with a foreign key - mysql

I'm having a problem with my SQL Tables. So I have my Usertable:
CREATE TABLE IF NOT EXISTS `user` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`NICKNAME` varchar(50) NOT NULL,
`PASSWORD` varchar(255) NOT NULL,
`EMAIL` varchar(50) DEFAULT NULL,
PRIMARY KEY (`NICKNAME`),
UNIQUE KEY `ID` (`ID`)
) ;
This table already exists and was created without any problems. I Want to create a score Table like this:
CREATE TABLE IF NOT EXISTS `scores` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`NICKNAME` varchar(50) NOT NULL,
`HIGHSCORE` int(11) NOT NULL,
PRIMARY KEY (`ID`),
FOREIGN KEY (NICKNAME) REFERENCES USER(Nickname)
)
On execution of the query I get this errormassage:
**#1005 - Kann Tabelle `xxxxx`.`scores` nicht erzeugen (Fehler: 150 "Foreign key constraint is incorrectly formed") (Details…)**
Its in German and says cant create Table, Error 150, I cant see where the key constraint is wrong, I used the same syntax in postgreSQL and it worked fine, but somehow MySQL is not accepting it. Any Ideas?

That is strange. If nickname is indeed the primary key, then your code should work.
It is much more nature, though, to use the auto-incremented column as the primary key. If you want the nickname, then use a join when you query.
So:
CREATE TABLE IF NOT EXISTS `scores` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
UserId int(11) NOT NULL,
`NICKNAME` varchar(50) NOT NULL,
`HIGHSCORE` int(11) NOT NULL,
PRIMARY KEY (`ID`),
FOREIGN KEY (UserId) REFERENCES USER(Id)
);

user - is a keyword.
It may be a good idea to use another table name e.g. "tblUser",
or use quotes again ``
FOREIGN KEY (NICKNAME) REFERENCES `USER`(ID)

Thanks to Mr. Gordon Linoff I was able to find my Mistake:
I had to declare NICKNAME to be declared UNIQUE, only then the FOREIGN KEY constraint could be added to other tables
CREATE TABLE IF NOT EXISTS `user` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`NICKNAME` varchar(50) NOT NULL,
`PASSWORD` varchar(255) NOT NULL,
`EMAIL` varchar(100) DEFAULT NULL,
PRIMARY KEY (`NICKNAME`),
UNIQUE KEY `ID` (`ID`),
UNIQUE KEY `NICKNAME` (`NICKNAME`)
);

Related

SQL 5.6 Foreign key statement error

i am new to SQL and i am trying out some simple create table statement but i am facing some problem with the foreign key at EMPLOYEEGROUP table. Below is a part of my create table statement
CREATE TABLE `User` (
`Userid` int(11) NOT NULL AUTO_INCREMENT,
`Username` VARCHAR(15) NOT NULL,
`Password` VARCHAR(15) NOT NULL,
PRIMARY KEY (Userid)
);
CREATE TABLE `Group` (
`GroupID` int(11) NOT NULL AUTO_INCREMENT,
`GroupName` VARCHAR(15) NOT NULL,
PRIMARY KEY (GroupID)
);
CREATE TABLE `EMPLOYEEGROUP` (
`EmployeeID` int(11) NOT NULL,
`AssignedGrp` int(11) NOT NULL,
CONSTRAINT EMPLOYEEGROUP_FK1 FOREIGN KEY (EmployeeID) REFERENCES User (Userid),
CONSTRAINT EMPLOYEEGROUP_FK2 FOREIGN KEY (AssignedGrp) REFERENCES Group (GroupID)
);
There is some issue with my EMPLOYEEGROUP_FK2 statement which i can't seem to solve it. any help would be appreciated. Thank you
In mysql GROUP is a reserved keyword. and you used group as table name
. but in table name you write group with `` . and when you take reference of group table you write group without ``. simple add `` in group name
Try blow query. it execute in my system hopfully execute also your system
CREATE TABLE `User` (
`Userid` int(11) NOT NULL AUTO_INCREMENT,
`Username` VARCHAR(15) NOT NULL,
`Password` VARCHAR(15) NOT NULL,
PRIMARY KEY (Userid)
);
CREATE TABLE `Group` (
`GroupID` int(11) NOT NULL AUTO_INCREMENT,
`GroupName` VARCHAR(15) NOT NULL,
PRIMARY KEY (GroupID)
);
CREATE TABLE `EMPLOYEEGROUP` (
`EmployeeID` int(11) NOT NULL,
`AssignedGrp` int(11) NOT NULL,
CONSTRAINT EMPLOYEEGROUP_FK1 FOREIGN KEY (EmployeeID) REFERENCES User (Userid),
CONSTRAINT EMPLOYEEGROUP_FK2 FOREIGN KEY (AssignedGrp) REFERENCES `Group` (GroupID)
);

MySQL table with a varchar column as foreign key

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 network_classes (
id TINYINT(1) UNSIGNED NOT NULL AUTO_INCREMENT,
category VARCHAR(80) NOT NULL,
PRIMARY KEY(id),
KEY `key_1` (`id`,`category`)
)
ENGINE=InnoDB;
CREATE TABLE networks (
id TINYINT(3) UNSIGNED NOT NULL AUTO_INCREMENT,
name VARCHAR(100) NOT NULL,
category VARCHAR(80) NOT NULL,
director_id TINYINT(3) UNSIGNED NULL,
director_name VARCHAR(100) NULL,
description VARCHAR(1000) NULL,
last_modified TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
user_id SMALLINT UNSIGNED NULL,
PRIMARY KEY(id),
KEY `networks_fk1` (`category`),
CONSTRAINT `networks_fk1` FOREIGN KEY (`category`) REFERENCES `network_classes` (`category`) ON DELETE NO ACTION,
INDEX networks_index2471(name),
INDEX networks_index2472(director_id, director_name)
)
ENGINE=InnoDB;
and I get this error:
[Err] 1215 - Cannot add foreign key constraint
I am using MySQL 5.6.12. How can I rewrite my query to fix it?
You can only have a foreign key referencing a unique field. Modify your network_classes table so that the category field is unique, like below
CREATE TABLE network_classes (
id TINYINT(1) UNSIGNED NOT NULL AUTO_INCREMENT,
category VARCHAR(80) NOT NULL,
PRIMARY KEY(id),
UNIQUE KEY `category_UNIQUE` (`category`),
KEY `key_1` (`id`,`category`)
)
ENGINE=InnoDB;
CREATE TABLE networks (
id TINYINT(3) UNSIGNED NOT NULL AUTO_INCREMENT,
name VARCHAR(100) NOT NULL,
category VARCHAR(80) NOT NULL,
director_id TINYINT(3) UNSIGNED NULL,
director_name VARCHAR(100) NULL,
description VARCHAR(1000) NULL,
last_modified TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
user_id SMALLINT UNSIGNED NULL,
PRIMARY KEY(id),
KEY `networks_fk1` (`category`),
CONSTRAINT `networks_fk1` FOREIGN KEY (`category`) REFERENCES `network_classes` (`category`) ON DELETE NO ACTION,
INDEX networks_index2471(name),
INDEX networks_index2472(director_id, director_name)
)
ENGINE=InnoDB;
You should then be able to add the foreign key you want
column types in the table and the referenced table do not match for
constraint
Why 2 varchar columns with same size not match in type? And of course the answer is obvious collation. Turns out that in the new table the column was UTF-8 instead of ASCII as in the referenced table. Changed to ascii and done.
The target of a FOREIGN KEY constraint needs to be indexed. Usually, it is a PRIMARY KEY so this isn't an issue, but in your case it's not (although it's part of a composite key, that's not enough)
Create an index on your network_classes.category field:
CREATE INDEX category_idx ON network_classes(category);
Then re-create your networks table.
For me, it was the charset that was missing. Just providing an example for reference.
CREATE TABLE `client` (
id int NOT NULL,
name varchar(255) NOT NULL,
email varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
created_at datetime NOT NULL,
created_by varchar(50) NOT NULL DEFAULT 'admin',
updated_at datetime NOT NULL,
updated_by varchar(50) NOT NULL DEFAULT 'admin',
PRIMARY KEY (id),
UNIQUE KEY name_UNIQUE (name),
KEY name_idx (name)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
create table `usecase` (`id` int NOT NULL AUTO_INCREMENT, `client` varchar(255) NOT NULL, `name` varchar(255), `description` varchar(1000), `rule_file` varchar(255), `parsed_rule_file` varchar(255), `archived` BOOLEAN DEFAULT 0, `state` ENUM('INITIATED','PARSED','UPLOADED', 'COMPLETE','FAILED'), `digest` varchar(255), `created_by` varchar(128) DEFAULT NULL, `created_at` datetime(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3), `updated_by` varchar(128) DEFAULT NULL, `updated_at` datetime(3) DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `uniq_usecase_id` (`client`,`name`), FOREIGN KEY (`client`) REFERENCES client(`name`))ENGINE=InnoDB DEFAULT CHARSET=latin1;
I had missed the line
DEFAULT CHARSET=latin1
in
CONSTRAINT `networks_fk1` FOREIGN KEY (`category`)
REFERENCES `network_classess` (`category`) ON DELETE NO ACTION,
you have used network_classess instead of network_classes (as in your create table script), so that table not exists.
EDIT
Name of your constraint is the same of key (networks_fk1) change ones.
I read better your DDL.
Your table network_classes has a primary key ID, so is correct put as foreign key a field to link your id field, the category field mustn't appear in your table network, but I think you must put fk_network_class (as int) linked to id (of network_classes)

#1215 - Cannot add foreign key constraint

I have this weird issue with creation of foreign key.
Given 2 tables:
CREATE TABLE IF NOT EXISTS `groupdeals` (
`groupdeals_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`product_id` int(10) NOT NULL,
`merchant_id` int(11) NOT NULL,
`minimum_qty` int(11) NOT NULL,
`maximum_qty` int(11) NOT NULL,
`target_met_email` int(11) NOT NULL,
`coupon_barcode` text NOT NULL,
`coupon_merchant_address` int(11) NOT NULL,
`coupon_merchant_contact` int(11) NOT NULL,
`coupon_expiration_date` date DEFAULT NULL,
`coupon_price` int(11) NOT NULL,
`coupon_fine_print` int(11) NOT NULL,
`coupon_highlights` int(11) NOT NULL,
`coupon_merchant_description` int(11) NOT NULL,
`coupon_business_hours` int(11) NOT NULL,
`coupon_merchant_logo` int(11) NOT NULL,
`coupon_additional_info` text NOT NULL,
`position` int(11) NOT NULL,
PRIMARY KEY (`groupdeals_id`),
KEY `groupdeals_id` (`groupdeals_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
and
CREATE TABLE IF NOT EXISTS `groupdeals_coupons` (
`coupon_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`groupdeals_id` int(11) NOT NULL,
`order_item_id` int(11) NOT NULL,
`coupon_code` varchar(255) NOT NULL DEFAULT '',
`redeem` varchar(255) NOT NULL DEFAULT '',
`status` varchar(255) NOT NULL DEFAULT '',
PRIMARY KEY (`coupon_id`),
KEY `fk_groupdeals_coupons_groupdeals1_idx` (`groupdeals_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
I try to add foreign key by executing following query:
ALTER TABLE `groupdeals_coupons`
ADD CONSTRAINT `fk_groupdeals_coupons_groupdeals1`
FOREIGN KEY (`groupdeals_id`)
REFERENCES `groupdeals` (`groupdeals_id`)
ON DELETE CASCADE
ON UPDATE CASCADE;
All I receive is Error:
#1215 - Cannot add foreign key constraint
Show engine innodb status
------------------------
LATEST FOREIGN KEY ERROR
------------------------
2013-08-17 13:47:49 7ff5dbb2c700 Error in foreign key constraint of table xxxxx/#sql-7b23_282b1a:
FOREIGN KEY (`groupdeals_id`)
REFERENCES `groupdeals` (`groupdeals_id`)
ON DELETE CASCADE
ON UPDATE CASCADE:
Cannot find an index in the referenced table where the
referenced columns appear as the first columns, or column types
in the table and the referenced table do not match for constraint.
Note that the internal storage type of ENUM and SET changed in
tables created with >= InnoDB-4.1.12, and such columns in old tables
cannot be referenced by such columns in new tables.
See http://dev.mysql.com/doc/refman/5.6/en/innodb-foreign-key-constraints.html
for correct foreign key definition.
The column groupdeals.groupdeals_id is a primary one, so I really can't understand where is a problem :|
Any hints?
Server type: Percona Server
Server version: 5.6.11-rc60.3-log - Percona Server (GPL), Release 60.3
Your types are inconsistent:
CREATE TABLE IF NOT EXISTS `groupdeals` (
`groupdeals_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
CREATE TABLE IF NOT EXISTS `groupdeals_coupons` (
[...]
`groupdeals_id` int(11) NOT NULL,
As you will see, in one table you have int unsigned. In the other, just int.
BTW, I noticed you have two keys on groupdeals_id. Is that on purpose?
CREATE TABLE IF NOT EXISTS `groupdeals` (
[...]
PRIMARY KEY (`groupdeals_id`),
KEY `groupdeals_id` (`groupdeals_id`)
Try these two steps to add foreign key:-
alter table groupdeals_coupons modify groupdeals_id int unsigned not null default 0;
ALTER TABLE groupdeals_coupons ADD CONSTRAINT fk_groupdeals_coupons_groupdeals1 FOREIGN KEY (groupdeals_id) references groupdeals (roupdeals_id);

on duplicate key update fails with error "Cannot add or update a child row"

I have a table with a compound primary key "name" and "id". The fields are actually "name","id","phone","amount","units","alias". I have the query
insert into MyTable (name,id,phone,amount) select "henry" as name, id,phone,amount from anotherTable
on duplicate key update phone=values(phone),amount=values(amount).
MySQL spits the following error:
Cannot add or update a child row: a foreign key constraint fails.
BTW, "id" is a foreign key.
Any help?
as requested below, the schema for other table is
CREATE TABLE `otherTable` (
`otherId` int(11) NOT NULL AUTO_INCREMENT,
`DOBId` int(11) NOT NULL,
`bankAccount` int(11) DEFAULT NULL,
`partialAmount` int(11) NOT NULL DEFAULT '0',
`id` int(11) NOT NULL,
`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`notes` varchar(299) DEFAULT NULL,
`latitude` decimal(8,5) DEFAULT NULL,
`longitude` decimal(8,5) DEFAULT NULL,
PRIMARY KEY (`otherId `),
KEY `DOBId ` (`DOBId `),
KEY `bankAccount ` (`bankAccount `),
KEY `id ` (`id `)
) ENGINE=InnoDB AUTO_INCREMENT=3305 DEFAULT CHARSET=utf8;
for myTable
CREATE TABLE `myTable` (
`name` int(11) NOT NULL,
`id` int(11) NOT NULL,
`appleNumber` int(11) DEFAULT NULL,
`amount` int(11) DEFAULT NULL,
`windowsNumber` int(11) DEFAULT NULL,
`phone` int(11) DEFAULT NULL,
`pens` int(11) DEFAULT NULL,
`pencils` int(11) DEFAULT NULL,
PRIMARY KEY (`name`,`id`),
KEY `id` (`id`),
CONSTRAINT `myTable_ibfk_1` FOREIGN KEY (`id`) REFERENCES `yet_another` (`id`)
The problem appears to be that the FK constraint you have on myTable is referencing the ids of yet_another, so when you are inserting ids from anotherTable you are breaking this FK constraint. Chances are there are ids in anotherTable that do not exist in yet_another table.
Understand this is a shot in the dark, based on the abstracted schema you posted. If you want a more solid answer, I'd have to see the actual schema.
The on duplicate key applies to the primary key. I take it you're using innodb. This is failing on a foreign key constraint. Which values of you table MyTable are foreign keys? Please post the create statement for the table that shows all keys and constraints for more detailed help.
Just a guess, but for grins I'm betting it's a column that's not in the insert that is a foreign key not allowing a null value.

Declare Foreign key in MySQL

I have these database
=== Invoices ===
id
status
description
=== Invoice Items ===
id
invoice_id (FK)
item_name
description
To make this table I have made this MySQL command
CREATE TABLE IF NOT EXISTS `nt_invoices` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`status` varchar(45) NOT NULL DEFAULT '',
`description` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=24 ;
CREATE TABLE IF NOT EXISTS `nt_invoice_items` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`invoice_id` int(11) NOT NULL,
`item_name` varchar(45) NOT NULL,
`description` text NOT NULL,
PRIMARY KEY (`id`),
KEY `invoice_id` (`invoice_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=12 ;
My problem is that I want to declare a foreign key in the invoice_items table and to make the invoice_id the foreign key of invoices table id. So how to write that command? Any help and suggestions will be highly appreciated.
MyISAM does not support foreign keys. You need to use InnoDB (which is a better choice in all aspects anyway). Then it's just like in any other SQL dialect:
`invoice_id` int(11) NOT NULL references nt_invoices(id),
P.S. Also, always use utf8 encoding everywhere. It will bite you in the ass if you don't.
You should have innodb engine type for using foreign keys.
CREATE TABLE IF NOT EXISTS `nt_invoice_items` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`invoice_id` int(11) NOT NULL references nt_invoices(id)
`item_name` varchar(45) NOT NULL,
`description` text NOT NULL,
PRIMARY KEY (`id`),
KEY `invoice_id` (`invoice_id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
OR if you want to use cascaded update delete:
CREATE TABLE IF NOT EXISTS `nt_invoice_items` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`invoice_id` int(11) NOT NULL,
`item_name` varchar(45) NOT NULL,
`description` text NOT NULL,
PRIMARY KEY (`id`),
KEY `invoice_id` (`invoice_id`),
FOREIGN KEY (invoice_id) REFERENCES nt_invoices(id)
ON DELETE CASCADE
ON UPDATE CASCADE,
) ENGINE=INNODB DEFAULT CHARSET=utf8;
You may also use ALTER command to declare FOREIGN KEY as follows:
Alter table table_name add foreign key(column_name)
references other_table_name(column);