MySQL Error 1451 - mysql

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

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

Insert into a table with forign key within the trigger of the other table in MySQL

I have a parent table in MySQL as follows:
CREATE TABLE `parentTBL` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`source_name` varchar(255) DEFAULT NULL,
`loc1` smallint(5) unsigned DEFAULT NULL,
`loc2` smallint(5) unsigned DEFAULT NULL,
`extra_info` json DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=latin1;
a child table:
CREATE TABLE `childTBL` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`source_names_id` int(10) unsigned NOT NULL,
`locations_id` int(10) unsigned NOT NULL,
`extra_info` json DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `fk_childTBL1_idx` (`source_names_id`),
KEY `fk_childTBL2_idx` (`locations_id`),
CONSTRAINT `fk_childTBL1` FOREIGN KEY (`source_names_id`) REFERENCES `source_names` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_childTBL2` FOREIGN KEY (`locations_id`) REFERENCES `locations` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
and these 2 tables:
CREATE TABLE `source_names` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`source_name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `source_name_UNIQUE` (`source_name`)
) ENGINE=InnoDB AUTO_INCREMENT=85 DEFAULT CHARSET=latin1;
CREATE TABLE `locations` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`loc1` smallint(5) unsigned DEFAULT NULL,
`loc2` smallint(5) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `loc1` (`loc1`,`loc2`)
) ENGINE=InnoDB AUTO_INCREMENT=43 DEFAULT CHARSET=latin1;
I have a trigger for parentTBL table before insert like this:
CREATE DEFINER=`root`#`localhost` TRIGGER `myDB`.`parentTBL_BEFORE_INSERT` BEFORE INSERT ON `parentTBL` FOR EACH ROW
BEGIN
INSERT IGNORE INTO source_names (source_name) VALUES (NEW.source_name);
INSERT IGNORE INTO locations (loc1,loc2) VALUES (NEW.loc1,NEW.loc2);
INSERT IGNORE INTO childTBL (source_names_id,locations_id,extra_info) VALUES (????,????,NEW.extra_info);
END
and I want to insert into childTBL and 2 other tables before inserting into parentTBL but I don't know what should I put in ???? fields in above trigger (third INSERT IGNORE. Move scroll to right)?
(It should be noted that I don't want to use SELECT because I have some millions records and fast insertion is important to me and also my problem is not solved with LAST_INSERT_ID() because it is possible that I need the source_names_id which is added before last_inserted in source_names table.)

Designing E-commerce database and mysql error

I am trying to make an e-commerce site from scratch. Currently I am trying to make the database.
These are the core tables that the database will have:
Customer: which will have email, username, password....
Customers_Session: Stores information about customer session in hash
Group: basically tells what permissions a customer will have
Category: the category type of a product
Product: information about a product such as name, and description...
Product_Price: Price info on products. This will store the different prices put for each product at various times.
Product_Variation: information about product images, and various colors or styles of a product.
Customer_Orders: What products a customer has ordered.
Customer_Reviews: Reviews made by customers on a product.
Reviewed Products: This table is created based on many to many relationship between the Product table and the Review Table.
Ordered products: This table is created based on the many to many relationship between the Product and the Orders Table.
Based on the above, I have come up with the sql code below:
--
-- Table structure for table `users`
--
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT ,
`username` varchar(30) NOT NULL,
`password` varchar(64) NOT NULL,
`first_name` varchar(50) NOT NULL,
`last_name` varchar(50) NOT NULL,
`email` varchar(50) NOT NULL,
`address` varchar(320) NOT NULL,
`zip` mediumint(5) NOT NULL,
`salt` varchar(40) NOT NULL,
`joined` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`group` tinyint(1) NOT NULL,
`dob` date NOT NULL,
`pic_url` varchar(225) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
--
--
-- Table structure for table `groups`
--
CREATE TABLE IF NOT EXISTS `groups` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) NOT NULL,
`permissions` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
--
-- This is for category table
--
CREATE TABLE IF NOT EXISTS `category`(
`category_id` tinyint(3) NOT NULL AUTO_INCREMENT,
`category_type` varchar(100) NOT NULL,
`category_description` varchar(160) NOT NULL,
PRIMARY KEY (`category_id`)
)ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
--
--
-- This is for product table
--
CREATE TABLE IF NOT EXISTS `products`(
`product_id` int(11) NOT NULL AUTO_INCREMENT,
`product_name` varchar(100) NOT NULL UNIQUE,
`product_description` varchar(160) NOT NULL,
`quantity` int(5) NOT NULL,
`product_code` varchar(4) NOT NULL,
`keywords` varchar(70) NOT NULL,
`category_id` tinyint(3),
PRIMARY KEY (`product_id`),
INDEX (`category_id`),
CONSTRAINT FOREIGN KEY (`category_id`) REFERENCES category(`category_id`) ON DELETE SET NULL
)ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
--
--
--
-- Table structure for table `bookings`
--
CREATE TABLE IF NOT EXISTS `bookings` (
`bookings_id` int(11) NOT NULL AUTO_INCREMENT,
`party_type` varchar(50) NOT NULL,
`location` varchar(100) NOT NULL,
`day` varchar(10) NOT NULL,
`time` smallint(6) NOT NULL,
`people_count` smallint(6) NOT NULL,
`booking_name` varchar(50) NOT NULL,
`booking_email` varchar(50) NOT NULL,
PRIMARY KEY (`bookings_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='This is for the bookings' AUTO_INCREMENT=1 ;
--
-- Dumping data for table `groups`
--
INSERT INTO `groups` (`id`, `name`, `permissions`) VALUES
(1, 'Administrator', '{"admin":1}'),
(2, 'Users', '{"users":2}');
--
-- Table Structure for Reviews
--
CREATE TABLE IF NOT EXISTS `customer_reviews`(
`reviews_id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11),
`rating` int(5) NOT NULL,
`comment` varchar(160) NOT NULL,
PRIMARY KEY(`reviews_id`),
INDEX (`user_id`),
CONSTRAINT FOREIGN KEY(`user_id`) REFERENCES users(`user_id`) ON DELETE SET NULL
)ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
--
--
-- Table structure for reviewed products This is a many relationshi btw reviews table and product
--
CREATE TABLE IF NOT EXISTS `reviewed_products`(
`product_id` int(11),
`reviews_id`int(11),
PRIMARY KEY(`product_id`,`reviews_id`),
CONSTRAINT FOREIGN KEY(`product_id`) REFERENCES products(`product_id`) ON DELETE SET NULL,
CONSTRAINT FOREIGN KEY(`reviews_id`) REFERENCES customer_reviews(`reviews_id`) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='This is for many to many cardinality btw reviews and products' AUTO_INCREMENT=1 ;
--
--
-- Table structure for table `orders`
--
CREATE TABLE IF NOT EXISTS `customer_orders` (
`order_id` int(11) NOT NULL AUTO_INCREMENT,
`order_time` int(11) NOT NULL,
`amount` int(5),
`confirmation_number` int(,
`user_id` int(11),
`product_id` int(11),
PRIMARY KEY (`order_id`),
INDEX (`user_id`),
CONSTRAINT FOREIGN KEY (`user_id`) REFERENCES users(`user_id`) ON DELETE RESTRICT
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
/* We need a new table since the customer_order and product is in a many to many relationship */
--
--
-- Table structure for table `curtomer_order_product`
--
CREATE TABLE IF NOT EXISTS `ordered_product`(
`product_id` int(11),
`order_id` int(11),
`quantity` smallint(5),
PRIMARY KEY(`product_id`,`order_id`),
INDEX (`product_id`,`order_id`),
CONSTRAINT FOREIGN KEY (`order_id`) REFERENCES customer_orders(`order_id`) ON DELETE RESTRICT,
CONSTRAINT FOREIGN KEY (`product_id`) REFERENCES products(`product_id`) ON DELETE RESTRICT
)ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
--
-- This is for price table
--
CREATE TABLE IF NOT EXISTS `product_price`(
`price_id` int(11) NOT NULL AUTO_INCREMENT,
`price` decimal(6,2) NOT NULL,
`product_id` int(11) NOT NULL,
PRIMARY KEY (`price_id`),
INDEX (`product_id`),
CONSTRAINT FOREIGN KEY (`product_id`) REFERENCES products(`product_id`)
)ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
--
--
-- Table structure for table `product_variations`
--
CREATE TABLE IF NOT EXISTS `product_variations`(
`variations_id` int(11) NOT NULL AUTO_INCREMENT,
`color_name` varchar(10) NOT NULL,
`color_value` char(6) NOT NULL,
`product_id` int(11),
`picture1` varchar(100) NOT NULL,
`picture2` varchar(100) NOT NULL,
`picture3` varchar(100) NOT NULL,
PRIMARY KEY (`variations_id`),
INDEX (`product_id`),
CONSTRAINT FOREIGN KEY (`product_id`) REFERENCES products(`product_id`) ON DELETE RESTRICT
)ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
--
--
-- Table structure for table `users_session`
--
CREATE TABLE IF NOT EXISTS `users_session` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`hash` varchar(64) NOT NULL,
PRIMARY KEY (`id`),
INDEX (`user_id`),
CONSTRAINT FOREIGN KEY(`user_id`) REFERENCES users(`user_id`) ON DELETE RESTRICT
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
The problem is that when I try to run the above code in PHPmyadmin, I get an error stating "Cannot add foreign key constraint". This starts to happen when creating the customer_Reviews table and any other subsequent tables that require foreign keys.
My questions are:
1. Would you recommend designing the database this way.
2. Why am I getting the "Cannot add foreign key constraint" error?
Thanks.
For a full quality review of your database design, you might try the Code Review sister site. At a glance, I don't see any glaring issues with your database design or your SQL.
The foreign key constraint is failing because you have misnamed the column in question.
CONSTRAINT FOREIGN KEY(`user_id`) REFERENCES users(`user_id`)
should be:
CONSTRAINT FOREIGN KEY(`user_id`) REFERENCES users(`id`)

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

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

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);