Error creating tables with foreign keys - mysql

I modelled a really simple DB for the first time and trying to insert the queries:
CREATE TABLE `product` (
`pid` varchar(255) NOT NULL,
`mfr` varchar(255) NULL,
`pnum` varchar(255) NOT NULL,
`ssku` varchar(255) NULL,
PRIMARY KEY (`pid`)
);
CREATE TABLE `detail` (
`pid` varchar(255) NOT NULL,
`sdesc` varchar(255) NULL,
`supplier` varchar(255) NULL,
PRIMARY KEY (`pid`)
);
CREATE TABLE `images` (
`pid` varchar(255) NOT NULL,
`url` varchar(255) NULL,
`alt` varchar(255) NULL,
`position` varchar(255) NULL,
PRIMARY KEY (`pid`)
);
ALTER TABLE `detail` ADD CONSTRAINT `fk_detail` FOREIGN KEY (`pid`) REFERENCES `product` ();
ALTER TABLE `images` ADD CONSTRAINT `pid` FOREIGN KEY () REFERENCES `product` ();
... but I get this error:
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 `product` ()' at line 1
what am I doing wrong?

You must pass the column name to the REFERENCES clause:
REFERENCES product(pid);
Also, you're creating a blank foreign key on the images constraint:
FOREIGN KEY () REFERENCES `product` ();

Related

How to resolve SQL ERROR 1604 Syntax error when I can't spot the issue?

I'm new to all of this and I am struggling to spot where the error in my syntax is for creating sql tables, any support is greatly appreciated:
The error I am recieving is :
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 ')
REFERENCES ims.orders ()
ON DELETE CASCADE
ON UPDATE CASCADE,
CO' at line 8
Which comes from running this code snippet:
CREATE TABLE IF NOT EXISTS `ims`.`orderline` (
`olid` INT NOT NULL AUTO_INCREMENT,
`oid` INT NOT NULL,
`iid` INT NOT NULL,
`quantity` INT NOT NULL,
PRIMARY KEY (`olid`),
CONSTRAINT `oid`
FOREIGN KEY ()
REFERENCES ims.orders ()
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT `iid`
FOREIGN KEY ()
REFERENCES ims.items ()
ON DELETE CASCADE
ON UPDATE CASCADE
);
From the database created with this schema:
drop schema ims;
CREATE SCHEMA IF NOT EXISTS `ims`;
USE `ims` ;
CREATE TABLE IF NOT EXISTS `ims`.`customers` (
`cid` INT(11) NOT NULL AUTO_INCREMENT,
`first_name` VARCHAR(40) NULL DEFAULT NULL,
`surname` VARCHAR(40) NULL DEFAULT NULL,
PRIMARY KEY (`cid`)
);
CREATE TABLE IF NOT EXISTS `ims`.`items` (
`iid` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(40) NULL DEFAULT NULL,
`price` DECIMAL(10,2) NOT NULL,
PRIMARY KEY (`iid`)
);
CREATE TABLE IF NOT EXISTS `ims`.`orders` (
`oid` INT(11) NOT NULL AUTO_INCREMENT,
`cid`INT(11) NOT NULL,
FOREIGN KEY (cid) REFERENCES ims.customers (cid)
ON DELETE CASCADE
ON UPDATE CASCADE,
PRIMARY KEY (`oid`)
);
CREATE TABLE IF NOT EXISTS `ims`.`orderline` (
`olid` INT NOT NULL AUTO_INCREMENT,
`oid` INT NOT NULL,
`iid` INT NOT NULL,
`quantity` INT NOT NULL,
PRIMARY KEY (`olid`),
CONSTRAINT `oid_fk`
FOREIGN KEY (`oid`)
REFERENCES ims.orders (oid)
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT `iid_fk`
FOREIGN KEY (`iid`)
REFERENCES ims.items (iid)
ON DELETE CASCADE
ON UPDATE CASCADE
);

MySQL ADD CONSTRAINT fail with [Err] 1215 - Cannot add foreign key constraint

I created two tables with the SQL:
CREATE TABLE `dinnertable` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`tableName` varchar(20) DEFAULT NULL,
`tableStatus` int(11) DEFAULT '0',
`orderDate` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
);
CREATE TABLE `food` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`foodName` varchar(20) DEFAULT NULL,
`foodType_id` int(11) DEFAULT NULL,
`price` double DEFAULT NULL,
`mprice` double DEFAULT NULL,
`remark` varchar(200) DEFAULT NULL,
`img` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`)
);
But I can not ALTER the food TABLE to ADD CONSTRAINT:
ALTER TABLE food ADD CONSTRAINT fk_food_foodType_id FOREIGN KEY(foodType_id) REFERENCES foodType(id);
With the error info:
[SQL] ALTER TABLE food ADD CONSTRAINT fk_food_foodType_id FOREIGN KEY(foodType_id) REFERENCES foodType(id);
[Err] 1215 - Cannot add foreign key constraint
You're referring to the foodType table in your foreign key constraint definition. You should create that table before adding a constraint to it.
Moreover, that table should have field id as a primary key, matching the type of foodType_id.

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;

Mysql: using two foreign keys to the same table

I'm using MySQL workbench to design a database. Server is mysql 5.5.6
I've defined a few foreign keys linking the "candidates" table to the "countries" table. I get this error:
Executing SQL script in server
ERROR: Error 1005: Can't create table 'customer.candidats' (errno: 150)
The thing is: i'm referencing twice the countries table: once for the "nationality" column, once for the user address's country of origin. Is that allowed? Is this the right way to do it?
Here is the generated code that seems to trigger the issue.
CREATE TABLE IF NOT EXISTS `customer`.`candidats` (
`id` INT NOT NULL AUTO_INCREMENT,
`nom` VARCHAR(40) NULL,
`prenom` VARCHAR(40) NULL,
`qualite` ENUM('0001','0002') NULL COMMENT '0001 = Madame\n0002 = Monsieur',
`sexe` SET('1','2') NULL COMMENT '1 = Femme\n2 = Homme',
`date_de_naissance` DATE NULL,
`Nationalite` INT NOT NULL,
`selor_bilinguisme` TINYINT(1) NULL,
`rue` VARCHAR(60) NULL,
`numero` VARCHAR(10) NULL,
`pays` INT NOT NULL,
`region` INT NOT NULL,
`localité` VARCHAR(40) NULL,
`code_postal` VARCHAR(10) NULL,
`email` VARCHAR(241) NULL,
`tel_domicile` VARCHAR(30) NULL,
`tel_bureau` VARCHAR(30) NULL,
`tel_mobile` VARCHAR(30) NULL,
`tel_prefere` ENUM('01','02','03') NULL DEFAULT '03',
PRIMARY KEY (`id`),
INDEX `fk_candidats_pays_idx` (`Nationalite` ASC, `pays` ASC),
INDEX `fk_candidats_régions1_idx` (`region` ASC),
CONSTRAINT `fk_candidats_pays`
FOREIGN KEY (`Nationalite` , `pays`)
REFERENCES `customer`.`pays` (`id` , `id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_candidats_régions1`
FOREIGN KEY (`region`)
REFERENCES `customer`.`régions` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
The "pays" table ("countries" in French)
CREATE TABLE IF NOT EXISTS `customer`.`pays` (
`id` INT NOT NULL AUTO_INCREMENT,
`nom_fr` VARCHAR(45) NULL,
`nom_nl` VARCHAR(45) NULL,
`nationalite_fr` VARCHAR(45) NULL,
`nationalite_nl` VARCHAR(45) NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `id_UNIQUE` (`id` ASC))
ENGINE = InnoDB
Your schema generator doesn't work correctly.
It should generate:
CONSTRAINT `fk_candidats_pays`
FOREIGN KEY (`pays`)
REFERENCES `customer`.`pays` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_candidats_Nationalite`
FOREIGN KEY (`Nationalite`)
REFERENCES `customer`.`pays` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
To your other question: This type of referencing seems strange when you see it the first time, but it's quite normal and I think there is no other way of constructing this type of relationship.

It it possible to add a foreign key constraint to a composite key in mysql?

So I have 2 tables.
subject_schedule:
CREATE TABLE IF NOT EXISTS `subject_schedule` (
`subject` varchar(10) NOT NULL,
`schedule_id` int(11) NOT NULL,
`id` int(11) NOT NULL,
PRIMARY KEY (`subject`,`schedule_id`),
KEY `schedule_id` (`schedule_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
and appointment:
CREATE TABLE IF NOT EXISTS `appointment` (
`work_plan` varchar(1000) DEFAULT NULL,
`date` date DEFAULT NULL,
`homework_given` varchar(1000) DEFAULT NULL,
`tutor_comments` varchar(1000) DEFAULT NULL,
`admin_comments` varchar(1000) DEFAULT NULL,
`id` int(11) NOT NULL AUTO_INCREMENT,
`schedule_id` int(11) NOT NULL,
`attended` tinyint(1) NOT NULL DEFAULT '1',
`arrival_time` time DEFAULT NULL,
`departure_time` time DEFAULT NULL,
`homework_completed` tinyint(1) NOT NULL DEFAULT '0',
`subject` varchar(10) NOT NULL,
PRIMARY KEY (`id`),
KEY `schedule_id` (`schedule_id`),
KEY `subject` (`subject`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=10004 ;
I want to create a foreign key which references the composite key in appointment. I have tried:
ALTER TABLE 'appointment'
ADD CONSTRAINT 'appointment_fk' FOREIGN KEY (`schedule_id`, `subject`)
REFERENCES 'subject_schedule' ('schedule_id', 'subject');
but it returns an error in PhpMyAdmin:
#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 ''appointment' ADD CONSTRAINT 'appointment_fk' FOREIGN KEY
(schedule_id, `su' at line 1
What am I doing wrong?
Is it better to just have an id as a primary key and reference that instead of using a composite key?
the columnNames shouldn't be wrap with single quotes because it will be converted to a string (not a column anymore)
ALTER TABLE appointment
ADD CONSTRAINT appointment_fk FOREIGN KEY (`schedule_id`, `subject`)
REFERENCES subject_schedule (schedule_id, subject);
SQLFiddle Demo