Cannot add a foreign key in mysql where a field is a unique index - mysql

I'm having problem adding a foreign key based on AUTH_ISLE_CODE:
Create Table: CREATE TABLE `AUTH_ACCOUNT` (
`ACCOUNT_ID` int(11) NOT NULL AUTO_INCREMENT,
`PASSWORD` varchar(20) DEFAULT NULL,
...
`AUTH_ISLE_ID` int(11) NOT NULL DEFAULT '1',
`AUTH_ISLE_CODE` varchar(5) NOT NULL DEFAULT 'AAAAA',
PRIMARY KEY (`ACCOUNT_ID`),
KEY `fk_ACCOUNT_ISLE` (`AUTH_ISLE_ID`),
CONSTRAINT `fk_ACCOUNT_ISLE` FOREIGN KEY (`AUTH_ISLE_ID`) REFERENCES `AUTH_ISLE` (`ISLE_ID`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=166 DEFAULT CHARSET=utf8
Create Table: CREATE TABLE `AUTH_ISLE` (
`ISLE_ID` int(11) NOT NULL AUTO_INCREMENT,
`NAME` varchar(100) DEFAULT NULL,
`CODE` varchar(5) NOT NULL DEFAULT 'AAAAA',
PRIMARY KEY (`ISLE_ID`),
UNIQUE KEY `CODE_UNIQUE` (`CODE`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8
the error I'm having is:
ERROR 1005 (HY000): Can't create table 'masterdata.#sql-73c1_57910' (errno: 150)
Is it something about the fact that the two tables have already a relationship with AUTH_ISLE_ID
Edit 1: the SHOW CREATE TABLE you see is the current situation. I'm trying to add just the constraint to AUTH_ISLE_CODE -> CODE from AUTH_ISLE

If this is a sequence of queries you are trying to create tables then it will always fail because you are referencing a table REFERENCES AUTH_ISLE (ISLE_ID) which is not created yet ,try creating first AUTH_ISLE table then create your second table AUTH_ACCOUNT,and when AUTH_ISLE is present you can simply reference its columns
CREATE TABLE `AUTH_ISLE` (
`ISLE_ID` int(11) NOT NULL AUTO_INCREMENT,
`NAME` varchar(100) DEFAULT NULL,
`CODE` varchar(5) NOT NULL DEFAULT 'AAAAA',
PRIMARY KEY (`ISLE_ID`),
UNIQUE KEY `CODE_UNIQUE` (`CODE`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
CREATE TABLE `AUTH_ACCOUNT` (
`ACCOUNT_ID` int(11) NOT NULL AUTO_INCREMENT,
`PASSWORD` varchar(20) DEFAULT NULL,
`AUTH_ISLE_ID` int(11) NOT NULL DEFAULT '1',
`AUTH_ISLE_CODE` varchar(5) NOT NULL DEFAULT 'AAAAA',
PRIMARY KEY (`ACCOUNT_ID`),
KEY `fk_ACCOUNT_ISLE` (`AUTH_ISLE_ID`),
CONSTRAINT `fk_ACCOUNT_ISLE` FOREIGN KEY (`AUTH_ISLE_ID`)
REFERENCES `AUTH_ISLE` (`ISLE_ID`)
ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=166 DEFAULT CHARSET=utf8;
Demo
insert into AUTH_ISLE (NAME,CODE) values('Test','Test');
insert into AUTH_ACCOUNT (PASSWORD,AUTH_ISLE_ID,AUTH_ISLE_CODE)
values('Test',last_insert_id(),'Test');
Insert 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 Foreign Key constraint fails to create with unexisting constraint

So I have two tables, customers and appointments.
Im trying to create a very simple FK relation between appointments.customer_id and customers.id, however when I do my ALTER TABLE trying to add the FK im getting this error:
MySQL said: Cannot add or update a child row: a foreign key constraint fails (wax.#sql-2c5_100, CONSTRAINT customer_fk FOREIGN KEY (id) REFERENCES customers (id) ON DELETE CASCADE ON UPDATE CASCADE)
This constraint "#sql-2c5_100" seems to be some randomly generated constraint, that I can not find ANYWHERE. I've looked on every table on the database, ive looked on all the tables on the information schema and it simply does not exist.
Thanks!
Edit:
Here's the create table outputs
CREATE TABLE `appointments` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`customer_id` int(11) unsigned NOT NULL,
`name` varchar(255) DEFAULT NULL
PRIMARY KEY (`id`),
KEY `customer_id` (`customer_id`)
) ENGINE=InnoDB AUTO_INCREMENT=290958 DEFAULT CHARSET=utf8;
CREATE TABLE `customers` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`first_name` varchar(255) NOT NULL DEFAULT '',
`last_name` varchar(255) NOT NULL DEFAULT '',
`phone` varchar(20) DEFAULT NULL
PRIMARY KEY (`id`),
KEY `sf_id` (`sf_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

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 Foreign Key Error

I want to create a database and connect it with two database. But I don't know when i create the Foreign Key to the second database (time_shift table) it always result error 150;
Here is the structure of table outlet:
And this is structure of table time_shift:
And this the query to create new table tide_cart:
create table `tide_chart` (
`id` int(10) not null auto_increment primary key,
`date` date null,
`outletId` int(11) not null,
`timeShiftId` int(11) not null,
`value` varchar(255) not null,
unique (`date`, `outletId`, `timeShiftId`),
foreign key (`outletId`) references `outlet`(`id`)
ON update cascade ON delete cascade,
foreign key (`timeShiftId`) references `time_shift`(`id`)
ON update cascade ON delete cascade
) engine=innoDB;
Please explain to me, why i get error when try to make foreign key connect to table time_shift?
Update: add dump export structure table for outlet and time_shift:
CREATE TABLE `outlet` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=5 ;
CREATE TABLE `time_shift` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`time_start` time NOT NULL,
`time_end` time NOT NULL,
`is_active` tinyint(4) NOT NULL DEFAULT '1',
`ref_area` int(11) NOT NULL DEFAULT '1',
PRIMARY KEY (`id`),
KEY `ref_area` (`ref_area`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=7 ;
You need to use the InnoDB engine for your tables. time_shift is using MyISAM.
You must define indexes for outletId and timeShiftId (either UNIQUE or KEY as needed) in order to be able to create a foreign key using that field.

MySQL Error 1451

Command:
DELETE FROM `meetings`.`meetingparticipants` WHERE `meetingparticipants`.`idParticipants` =503 AND `meetingparticipants`.`idMeetings` =83
I know I have a simple error in my database. I am attempting to delete a row from the meeting participants table and receiving the following error:
#1451 - Cannot delete or update a parent row: a foreign key constraint fails (`meetings`.`invoices`, CONSTRAINT `fk_meetingid` FOREIGN KEY (`fk_meetingid`) REFERENCES `meetingparticipants` (`idMeetings`) ON DELETE NO ACTION ON UPDATE NO ACTION)
Any ideas? I think I need a foreign key relationship between the participant table and the meeting-participant table with updates, but I rather confirm or see if there are any suggestions??
CREATE TABLE IF NOT EXISTS `invoices` (
`idinvoices` int(11) NOT NULL AUTO_INCREMENT,
`fk_invoiceType` int(11) DEFAULT NULL,
`DocNum` varchar(10) DEFAULT NULL,
`DZ` varchar(9) DEFAULT NULL,
`Amount` decimal(10,2) DEFAULT NULL,
`fk_meetingid` int(11) DEFAULT NULL,
`fk_participantid` int(11) DEFAULT NULL,
`invoiceNotes` varchar(255) DEFAULT NULL,
`invoiceDocuments` blob,
PRIMARY KEY (`idinvoices`),
UNIQUE KEY `DOC_Num` (`DocNum`),
KEY `fk_invoiceType` (`fk_invoiceType`),
KEY `fk_meetingid` (`fk_meetingid`),
KEY `fk_participantid` (`fk_participantid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1014 ;
-- --------------------------------------------------------
--
-- Table structure for table `invoicestatus`
--
CREATE TABLE IF NOT EXISTS `invoicestatus` (
`idinvoiceStatus` int(11) NOT NULL AUTO_INCREMENT,
`invoiceStatus` varchar(45) NOT NULL,
PRIMARY KEY (`idinvoiceStatus`),
UNIQUE KEY `invoiceStatus_UNIQUE` (`invoiceStatus`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=23 ;
-- --------------------------------------------------------
--
-- Table structure for table `invoicestatushistory`
--
CREATE TABLE IF NOT EXISTS `invoicestatushistory` (
`fk_invoiceStatus` int(11) DEFAULT NULL,
`statusStamp` datetime DEFAULT NULL,
`fk_idinvoices` int(11) NOT NULL,
`idinvoiceStatusHistory` int(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`idinvoiceStatusHistory`,`fk_idinvoices`),
KEY `invoiceStatusHistory` (`fk_invoiceStatus`),
KEY `invoiceid` (`fk_idinvoices`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1015 ;
-- --------------------------------------------------------
--
-- Table structure for table `invoicetypes`
--
CREATE TABLE IF NOT EXISTS `invoicetypes` (
`idinvoiceTypes` int(11) NOT NULL AUTO_INCREMENT,
`invoiceType` varchar(45) DEFAULT NULL,
PRIMARY KEY (`idinvoiceTypes`),
UNIQUE KEY `invoiceType_UNIQUE` (`invoiceType`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=21 ;
-- --------------------------------------------------------
--
-- Table structure for table `meetingparticipants`
--
CREATE TABLE IF NOT EXISTS `meetingparticipants` (
`idParticipants` int(11) NOT NULL,
`idMeetings` int(11) NOT NULL,
`invited` tinyint(1) DEFAULT NULL,
`attended` tinyint(1) DEFAULT NULL,
`travelCostsReimbursed` tinyint(1) DEFAULT NULL,
`ParticipantFeeEligible` tinyint(1) DEFAULT NULL,
`ParticipantFeeProcessed` tinyint(1) DEFAULT NULL,
PRIMARY KEY (`idParticipants`,`idMeetings`),
KEY `idParticipants` (`idParticipants`),
KEY `idMeetings` (`idMeetings`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Table structure for table `meetings`
--
CREATE TABLE IF NOT EXISTS `meetings` (
`idmeetings` int(11) NOT NULL AUTO_INCREMENT,
`meetingName` varchar(45) NOT NULL,
`beginDate` date DEFAULT NULL,
`endDate` date DEFAULT NULL,
`location` varchar(45) DEFAULT NULL,
`meetingNotes` varchar(255) DEFAULT NULL,
`meetingDocuments` blob,
`fk_programID` int(110) DEFAULT NULL,
PRIMARY KEY (`idmeetings`),
UNIQUE KEY `meetingName_UNIQUE` (`meetingName`),
KEY `programid` (`fk_programID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=85 ;
-- --------------------------------------------------------
--
-- Table structure for table `participants`
--
CREATE TABLE IF NOT EXISTS `participants` (
`idparticipants` int(11) NOT NULL AUTO_INCREMENT,
`firstName` varchar(45) DEFAULT NULL,
`lastName` varchar(45) NOT NULL,
`preferredName` varchar(75) DEFAULT NULL,
`email` varchar(45) DEFAULT NULL,
`affiliation` varchar(45) DEFAULT NULL,
`foreignNational` tinyint(1) DEFAULT NULL,
`grantPaid` tinyint(1) DEFAULT NULL,
`bannerid` varchar(9) DEFAULT NULL,
`participantNotes` varchar(255) DEFAULT NULL,
`participantDocuments` blob,
`visaType` int(11) DEFAULT NULL,
PRIMARY KEY (`idparticipants`),
UNIQUE KEY `bannerid_UNIQUE` (`bannerid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=507 ;
-- --------------------------------------------------------
--
-- Table structure for table `programs`
--
CREATE TABLE IF NOT EXISTS `programs` (
`idprograms` int(11) NOT NULL AUTO_INCREMENT,
`ProgramName` varchar(45) NOT NULL,
PRIMARY KEY (`idprograms`),
UNIQUE KEY `ProgramName_UNIQUE` (`ProgramName`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=21 ;
-- --------------------------------------------------------
--
-- Table structure for table `users`
--
CREATE TABLE IF NOT EXISTS `users` (
`userID` int(11) NOT NULL AUTO_INCREMENT,
`userName` varchar(25) NOT NULL,
`userPassword` varchar(10) NOT NULL DEFAULT 'password',
`userLevel` int(11) NOT NULL,
PRIMARY KEY (`userID`),
UNIQUE KEY `userName` (`userName`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;
-- --------------------------------------------------------
--
-- Table structure for table `visatypes`
--
CREATE TABLE IF NOT EXISTS `visatypes` (
`idvisaTypes` int(11) NOT NULL AUTO_INCREMENT,
`visaType` varchar(45) DEFAULT NULL,
`paymentInstructions` varchar(500) DEFAULT NULL,
PRIMARY KEY (`idvisaTypes`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=27 ;
--
-- Constraints for dumped tables
--
--
-- Constraints for table `invoices`
--
ALTER TABLE `invoices`
ADD CONSTRAINT `fk_invoiceType` FOREIGN KEY (`fk_invoiceType`) REFERENCES `invoicetypes` (`idinvoiceTypes`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `fk_meetingid` FOREIGN KEY (`fk_meetingid`) REFERENCES `meetingparticipants` (`idMeetings`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `fk_participantid` FOREIGN KEY (`fk_participantid`) REFERENCES `meetingparticipants` (`idParticipants`) ON DELETE NO ACTION ON UPDATE NO ACTION;
--
-- Constraints for table `invoicestatushistory`
--
ALTER TABLE `invoicestatushistory`
ADD CONSTRAINT `invoiceid` FOREIGN KEY (`fk_idinvoices`) REFERENCES `invoices` (`idinvoices`) ON DELETE NO ACTION ON UPDATE CASCADE,
ADD CONSTRAINT `invoiceStatusHistory` FOREIGN KEY (`fk_invoiceStatus`) REFERENCES `invoicestatus` (`idinvoiceStatus`) ON DELETE NO ACTION ON UPDATE CASCADE;
--
-- Constraints for table `meetings`
--
ALTER TABLE `meetings`
ADD CONSTRAINT `programid` FOREIGN KEY (`fk_programID`) REFERENCES `programs` (`idprograms`) ON DELETE NO ACTION ON UPDATE NO ACTION;
You have a foreign key constraint on the invoices table that is named "fk_meetingid", but references the meetingparticipants table, which is an association table. It would seem to me that if an invoice were linked to a meeting that it should be linked directly to the meetings table.
From the manual:
http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html
NO ACTION: A keyword from standard SQL. In MySQL, equivalent to
RESTRICT. InnoDB rejects the delete or update operation for the parent
table if there is a related foreign key value in the referenced table.
Some database systems have deferred checks, and NO ACTION is a
deferred check. In MySQL, foreign key constraints are checked
immediately, so NO ACTION is the same as RESTRICT.
If I understand your schema, (which is unlikely after looking at it for 30 seconds), you probably want to use ON DELETE CASCADE so that a participants invoices are deleted when you delete the participant. If you need to keep the invoices but delete the participant then choose ON DELETE SET NULL