Mysql foreign key - mysql

When trying to create a table and alter it with the below query:
CREATE TABLE `sms_codes` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`code` varchar(6) NOT NULL,
`status` int(1) NOT NULL DEFAULT '0',
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `user_id` (`user_id`)
)
ALTER TABLE `sms_codes`
ADD CONSTRAINT `sms_codes_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
I got the error:
#1064 - 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 'ALTER TABLE `sms_codes` ADD CONSTRAINT `sms_codes_ibfk_1` FOREIGN KEY (`user_' at line 11

Each statement need to separate by the delimiter ;. So add the ; in end of the CREATE TABLE in the same way how you added ; in end of the ALTER TABLE statement:
In this line:
KEY `user_id` (`user_id`)
); <-- here

Related

Error 1215 on adding foreign key. Help me with what I haven't tried

I'm trying to set a foreign key relationship between two existing table but for some reason which I'm missing I keep getting this error 1215.
The relevant fields of the two tables are:
CREATE TABLE `approvals` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`id_contract` int(11) NOT NULL,
`id_user` int(11) NOT NULL,
`lang` varchar(8) NOT NULL,
`request_ts` datetime NOT NULL,
`version` int(11) NOT NULL,
-- more nullable columns here with no indexing/relationships
PRIMARY KEY (`id`),
KEY `approval_id_user` (`id_user`),
KEY `version` (`version`,`lang`,`id_contract`),
CONSTRAINT `approval_id_user` FOREIGN KEY (`id_user`)
REFERENCES `users` (`iduser`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=1079 DEFAULT CHARSET=utf8
CREATE TABLE `version` (
`idversion` int(11) NOT NULL,
`idcontract` int(11) NOT NULL,
`language` varchar(8) NOT NULL,
PRIMARY KEY (`idversion`,`idcontract`,`language`),
KEY `fk_version_contracts_idx` (`idcontract`),
CONSTRAINT `fk_kidversion_contracts` FOREIGN KEY (`idcontract`)
REFERENCES `contracts` (`id_contract`)
ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8
What have I tried
First thing I checked is the persistency:
SELECT * FROM approvals a
WHERE NOT EXISTS (
SELECT 1 FROM version v
WHERE v.idcontract = a.id_contract AND v.language = a.lang
AND v.idversion = a.version);
which resulted in 0 rows returned out of 701, ok my db should be good from the data pov.
So I checked the collation and for some reason the version table was latin1 vs utf8_generic_ci, ok so I restored the version table to utf8 with this.
ALTER TABLE `kidversion`
COLLATE = utf8_general_ci;
-- and for good measure
ALTER TABLE `kidversion`
CHANGE COLUMN `language` `language` VARCHAR(8)
CHARACTER SET 'utf8' COLLATE 'utf8_general_ci' NOT NULL;
But at this point I'm still getting an error while trying to create the foreign key:
ALTER TABLE `approvals`
ADD CONSTRAINT `approval_ibfk_1`
FOREIGN KEY (`version` , `lang` , `id_contract`)
REFERENCES `version` (`idversion` , `language` , `idcontract`)
ON DELETE NO ACTION
ON UPDATE NO ACTION;
And that results in a 1215 in every step I made. Surely I'm missing something.. can anyone help me out with this?
FOREIGN KEY (version , lang , id_contract) REFERENCES version (idversion , language , idcontract) AND PRIMARY KEY (idversion,idcontract,language) don't match fields have to be in the same order as well as same type.
'In the referencing table, there must be an index where the foreign key columns are listed as the first columns in the same order.' - https://dev.mysql.com/doc/refman/5.6/en/create-table-foreign-keys.html

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

MySQL FOREIGN KEY Constraints Syntax

When I'm going to execute this code, I'm getting this error message:
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 'ADD CONSTRAINT fk_pay_grade_scale FOREIGN KEY pay_scale_id
REFERENCES `pay_s' at line 11
But I don't understand the problem. Your help is appreciated!
CREATE TABLE IF NOT EXISTS `pay_grades` (
`pay_grade_id` int(20) NOT NULL,
`pay_scale_id` tinyint(4) NOT NULL,
`name` varchar(100) NOT NULL,
`basic_salary` decimal(10,2) NOT NULL,
`status` int(2) NOT NULL DEFAULT '1',
PRIMARY KEY (`pay_grade_id`),
INDEX (`pay_scale_id`, `pay_grade_id`),
ADD CONSTRAINT `fk_pay_grade_scale` FOREIGN KEY `pay_scale_id` REFERENCES `pay_scales`(`id`) ON UPDATE CASCADE ON DELETE RESTRICT
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `pay_scales` (
`id` tinyint(4) NOT NULL,
`name` varchar(100) NOT NULL,
PRIMARY KEY(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
You can not use ADD CONSTRAINT in a CREATE TABLE declaration.
Declare your constraint after creating the table or in the CREATE TABLE.
First solution: Add the constraint in CREATE TABLE
CREATE TABLE IF NOT EXISTS `pay_grades` (
`pay_grade_id` int(20) NOT NULL,
`pay_scale_id` tinyint(4) NOT NULL,
`name` varchar(100) NOT NULL,
`basic_salary` decimal(10,2) NOT NULL,
`status` int(2) NOT NULL DEFAULT '1',
PRIMARY KEY (`pay_grade_id`),
INDEX (`pay_scale_id`, `pay_grade_id`),
FOREIGN KEY (`pay_scale_id`) REFERENCES `pay_scales`(`id`) ON UPDATE CASCADE ON DELETE RESTRICT
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Second solution: Alter table to add the constraint
Create your table without the constraint, and then add your constraint as follow:
ALTER TABLE `pay_grades`
ADD CONSTRAINT `pay_scale_id` FOREIGN KEY REFERENCES `pay_scales`(`id`)
ON UPDATE CASCADE ON DELETE RESTRICT;
MySQL documentation for foreign keys declaration.
It seems the difference in order of table creation. First create primary key table than create the table of foreign key.
CREATE TABLE IF NOT EXISTS `pay_scales` (
`id` tinyint(4) NOT NULL,
`name` varchar(100) NOT NULL,
PRIMARY KEY(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `pay_grades` (
`pay_grade_id` int(20) NOT NULL,
`pay_scale_id` tinyint(4) NOT NULL,
`name` varchar(100) NOT NULL,
`basic_salary` decimal(10,2) NOT NULL,
`status` int(2) NOT NULL DEFAULT '1',
PRIMARY KEY (`pay_grade_id`),
INDEX (`pay_scale_id`, `pay_grade_id`),
ADD CONSTRAINT `fk_pay_grade_scale` FOREIGN KEY `pay_scale_id` REFERENCES `pay_scales`(`id`) ON UPDATE CASCADE ON DELETE RESTRICT
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Error #1064 near "REFERENCES" while adding a foreign key

I keep getting error 1064 while trying to create a foreign key:
ALTER TABLE `zajimavost`
ADD CONSTRAINT FK_zaj_bod
FOREIGN KEY def_bod
REFERENCES `bod`(`gid`)
ON UPDATE CASCADE ON DELETE CASCADE;
It complains:
#1064 - 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 'REFERENCES `bod`(`gid`)
ON UPDATE CASCADE ON DELETE CASCADE' at line 4
I tried it with or without the backticks, the problem is always the same.
My tables:
CREATE TABLE `zajimavost` (
`zaj_id` int(11) NOT NULL,
`lok_id` int(11) NOT NULL,
`nazev` varchar(255) COLLATE utf8_czech_ci NOT NULL,
`kategorie` int(11) NOT NULL DEFAULT '1',
`datace_od` int(11) NOT NULL DEFAULT '31',
`datace_do` int(11) NOT NULL DEFAULT '60',
`def_bod` int(11) DEFAULT NULL,
PRIMARY KEY (`zaj_id`),
KEY `ck_zaj_lok` (`lok_id`),
KEY `zaj_id` (`zaj_id`),
KEY `FK_zaj_kat` (`kategorie`),
KEY `FK_zaj_bod` (`def_bod`),
CONSTRAINT `FK_zaj_kat` FOREIGN KEY (`kategorie`) REFERENCES `kategorie` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_zaj_lok` FOREIGN KEY (`lok_id`) REFERENCES `lokalita` (`lok_id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_czech_ci
CREATE TABLE `bod` (
`gid` int(11) NOT NULL AUTO_INCREMENT,
`geom` point DEFAULT NULL,
`radius` int(4) NOT NULL DEFAULT '50',
PRIMARY KEY (`gid`)
) ENGINE=InnoDB AUTO_INCREMENT=30 DEFAULT CHARSET=utf8 COLLATE=utf8_czech_ci
There are data in the tables.
So how to solve it?
You need to use () in child table column name while adding foreign key, Try this one
ALTER TABLE zajimavost
ADD CONSTRAINT FK_zaj_bod
FOREIGN KEY (def_bod) REFERENCES `bod`(`gid`)
ON UPDATE CASCADE ON DELETE CASCADE;

How to update many-to-many related objects with Entity framework 1 & MySQL?

I have such a problem. I'm using EF1 with VS2008 SP1 & MySQL with MySQL Connector/Net 6.3.4
My database schema looks like this:
CREATE TABLE IF NOT EXISTS `credential` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;
CREATE TABLE IF NOT EXISTS `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;
CREATE TABLE IF NOT EXISTS `user_credential` (
`user_id` int(11) NOT NULL,
`credential_id` int(11) NOT NULL,
KEY `credential_id` (`credential_id`),
KEY `user_id` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
ALTER TABLE `user_credential`
ADD CONSTRAINT `user_credential_ibfk_2` FOREIGN KEY (`credential_id`) REFERENCES `credential` (`id`) ON DELETE CASCADE,
ADD CONSTRAINT `user_credential_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE CASCADE;
While I'm trying to execute the folowing code I have exception that I cannot understand
var entities = new studyEntities();
var user = new User { Name = "test" };
var credential = new Credential { Name = "admin" };
entities.AddToCredentialSet(credential);
entities.AddToUserSet(user);
entities.SaveChanges();
user.Credentials.Add(credential);
entities.SaveChanges(); // He I have a strange exception thrown
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 '(SELECT
`user_credential`.`credential_id`,
`user_credential`.`user_' at line 1
What does it mean? How can I see the whole query to seek the problem in it? or maybe what I'm doing wrong?
I had the same error because I had no primary key in the middle table.
This fixed it for me:
CREATE TABLE IF NOT EXISTS `user_credential` (
`user_id` int(11) NOT NULL,
`credential_id` int(11) NOT NULL,
PRIMARY KEY(`user_id`, `credential_id`)
KEY `user_id` (`user_id`)
CONSTRAINT .... FOREIGN KEY....
CONSTRAINT .... FOREIGN KEY....
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Looks like a bug in Connector /NET.
We have made a test, this code succeeded in dotConnect fro MySQL.
Add a primary key to the many-to-many table.
So if your table is
CREATE TABLE If Not Exists SubsidiaryMapping
(
CompanyId bigint NOT NULL,
SubsidiaryId bigint NOT NULL,
-- Add Primary Key composing exisiting keys
-- Following fixed issue for me
PRIMARY KEY(CompanyId , SubsidiaryId ),
CONSTRAINT .... FOREIGN KEY....
CONSTRAINT .... FOREIGN KEY....
);