It it possible to add a foreign key constraint to a composite key in mysql? - 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

Related

Why I am having a this error on phpmyadmin: Error creating foreign key on revision (check data types)?

I´m trying to create Foreign Keys in phpmyadmin, but I get this error:
Error creating foreign key on revision (check data types)
I don´t understand it because the data types are equal. So, what I want is to create a Foreign Key from 'acoustictreatment' to 'filterspecifications' which contains tag, offerid and revision. But I get the error that I mentioned.
This are my tables:
CREATE TABLE `offer` (
`projectid` varchar(20) NOT NULL,
`customer` varchar(255) NOT NULL,
`creator` varchar(255) NOT NULL,
`date` date NOT NULL,
`revision` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE `offer`
ADD PRIMARY KEY (`projectid`,`revision`);
CREATE TABLE `filterspecifications` (
`tag` varchar(100) NOT NULL,
`gasFlow` double NOT NULL,
`dustToHandle` double NOT NULL,
`offerid` varchar(20) NOT NULL,
`selectedFilter` varchar(20) NOT NULL,
`revision` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE `filterspecifications`
ADD PRIMARY KEY (`tag`,`offerid`,`revision`),
ADD KEY `offerid` (`offerid`,`revision`);
ALTER TABLE `filterspecifications`
ADD CONSTRAINT `filterspecifications_ibfk_1`
FOREIGN KEY (`offerid`,`revision`) REFERENCES `offer` (`projectid`, `revision`) ON DELETE CASCADE ON UPDATE CASCADE;
CREATE TABLE `acoustictreatment` (
`tag` varchar(100) NOT NULL,
`offerid` varchar(20) NOT NULL,
`outputFanSilencer` tinyint(1) NOT NULL,
`fanAcousticInsulation` tinyint(1) NOT NULL,
`revision` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE `acoustictreatment`
ADD PRIMARY KEY (`tag`,`offerid`,`revision`);
The solution that I found is to delete the 'acoustictreatment' table and create it again with the foreign key from the beginning. Because what I was trying to do was to create all the tables and then create the foreign keys, but that didn´t work for me

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 error 1215, even though both colums are of the same type and are NOT NULL

Parent table team_entrant:
CREATE TABLE IF NOT EXISTS `team_entrant` (
`entrant_number` tinyint(4) NOT NULL,
`qualifying_position` tinyint(4) NOT NULL,
`qualifying_time` time(3) NOT NULL,
`grid_position` tinyint(4) DEFAULT NULL,
`best_race_time` datetime DEFAULT NULL,
`final_position` tinyint(4) DEFAULT NULL,
`dnf_reason` varchar(45) DEFAULT NULL,
`team_id` int(11) NOT NULL,
`competition_year` date NOT NULL,
PRIMARY KEY (`entrant_number`),
KEY `fk_team_entrant_team1_idx` (`team_id`),
CONSTRAINT `fk_team_entrant_team1` FOREIGN KEY (`team_id`) REFERENCES `team` (`team_id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Child table/Associative table entrant_drivers:
CREATE TABLE IF NOT EXISTS `entrant_drivers` (
`entrant_number` tinyint(4) NOT NULL,
`competition_year` date NOT NULL,
`driver_id` int(11) NOT NULL,
PRIMARY KEY (`entrant_number`,`competition_year`,`driver_id`),
CONSTRAINT `ed_entrant_fk` FOREIGN KEY (`entrant_number`) REFERENCES `team_entrant` (`entrant_number`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
At the time the team_entrant column competition_year did not exist.
HeidiSQL refuses to execute the following code:
ALTER table entrant_drivers ADD CONSTRAINT ed_comp_year_fk FOREIGN KEY (competition_year) REFERENCES team_entrant(competition_year);
SQL Error (1215): Cannot add foreign key constraint
Extraneous table, driver involved with the associative table:
-- Dumping structure for table 99_lemans_db1.driver
CREATE TABLE IF NOT EXISTS `driver` (
`driver_id` int(11) NOT NULL,
`driver_name` varchar(64) NOT NULL,
`driver_nationality` varchar(32) NOT NULL,
`driver_birth_day` date NOT NULL,
`driver_best_previous_finish_class` varchar(8) DEFAULT NULL,
`driver_best_previous_finish_position` tinyint(4) DEFAULT NULL,
`team_entrant_id` int(11) NOT NULL,
PRIMARY KEY (`driver_id`,`team_entrant_id`),
KEY `fk_driver_team_entrant1_idx` (`team_entrant_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Any assistance would be appreciated.
The parent column must be designated as an index/primary key.
team_entrant is supposed to be made up of the composite primary keys (entrant number, competition year).

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;

Adding new column to table as foreign key

I am having difficult time trying to add a column to my sql table that will be a foreign key to another table. I'm getting the following 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 ''description_id' INT,
ADD FOREIGN KEY (description_id)
REFERENCES description(de' at line 2
From my query:
ALTER TABLE images
ADD COLUMN 'description_id' INT,
ADD FOREIGN KEY (description_id)
REFERENCES description(description_id)
Here is my table, where I am trying to add the column to:
CREATE TABLE `images` (
`id` int(5) NOT NULL AUTO_INCREMENT,
`pattern` varchar(225) DEFAULT NULL,
`color` varchar(225) DEFAULT NULL,
`imageUrl` varchar(225) DEFAULT NULL,
`imageSource` varchar(225) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=47 DEFAULT CHARSET=latin1;
Here is the table that is being connected:
CREATE TABLE `description` (
`description_id` int(11) NOT NULL,
`color` varchar(255) DEFAULT NULL,
`pattern` varchar(255) DEFAULT NULL,
`body` varchar(255) DEFAULT NULL,
PRIMARY KEY (`description_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
You can't ALTER TABLE ADD, ADD. Try:
ALTER TABLE images
ADD COLUMN 'description_id' INT
REFERENCES description(description_id)