mysql composite foreign key referencing more than 2 attributes - mysql

Hi I have a table with 3 attributes as primary key
Products:
PRIMARY KEY (product_name,category,product_type).
Now i am referencing this composite primary key in another table
order_details:
foreign key(product_name,product_type,category) references products(product_name,product_type,category)
however I am getting an error in the console saying missing parenthesis and I am not able to add the foreign key. But if i add only 2 column names in the reference(example : "foreign key(product_name,product_type,category) references products(product_name,product_type)
") the query is not giving an error.
Please help me to resolve this issue. Please find my code below
CREATE TABLE `products` (
`product_name` varchar(45) NOT NULL,
`product_type` varchar(45) NOT NULL,
`category` varchar(45) NOT NULL,
`product_desc` varchar(150) DEFAULT NULL,
`unit_price` int(11) NOT NULL,
`supplier_id` int(11) NOT NULL,
`units_in_stock` int(11) NOT NULL,
PRIMARY KEY (`product_name`,`category`,`product_type`),
INDEX (product_name,category,product_type),
CONSTRAINT `supplier_prod_table_fkey` FOREIGN KEY (`supplier_id`) REFERENCES
`supplier` (`supplier_id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=INNODB;
CREATE TABLE `order_details` (
`order_id` int(11) NOT NULL AUTO_INCREMENT,
`product_name` varchar(45) NOT NULL,
`product_type` varchar(45) NOT NULL,
`category` varchar(45) NOT NULL,
`quantity` int(11) DEFAULT NULL,
CONSTRAINT `orderid_fkey` FOREIGN KEY (`order_id`) REFERENCES `orders`
(`order_id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
PRIMARY KEY (`order_id`,`product_name`,`product_type`,`category`),
INDEX (product_name,product_type,category),
foreign key(product_name,product_type,category) references products(product_name,product_type,category)
);

Fields in REFERENCES and in correspondent indices must go in the same order in both tables, i.e. (product_name, category, product_type).
CREATE TABLE `order_details` (
`order_id` int(11) NOT NULL AUTO_INCREMENT,
`product_name` varchar(45) NOT NULL,
`product_type` varchar(45) NOT NULL,
`category` varchar(45) NOT NULL,
`quantity` int(11) DEFAULT NULL,
CONSTRAINT `orderid_fkey` FOREIGN KEY (`order_id`) REFERENCES `orders`
(`order_id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
PRIMARY KEY (`order_id`,`product_name`,`product_type`,`category`),
INDEX (product_name,category,product_type),
FOREIGN KEY(product_name,category,product_type) REFERENCES products(product_name,category,product_type)
);

Related

MySQL Missing comma before start of a new alter operation. (near "ADD" at position 255)

I have a problem
my code
_________
-- phpMyAdmin SQL Dump
-- version 4.7.4
-- https://www.phpmyadmin.net/
--
-- --------------------------------------------------------
CREATE TABLE IF NOT EXISTS `country` (
`id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
`alpha2` varchar(2) NOT NULL,
`alpha3` varchar(3) NOT NULL,
`name` varchar(45) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `alpha2` (`alpha2`),
UNIQUE KEY `alpha3` (`alpha3`)
) ENGINE=InnoDB;
--
-- `user` table structure
--
CREATE TABLE IF NOT EXISTS `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`firstname` varchar(50) NOT NULL,
`lastname` varchar(50) NOT NULL,
`email` varchar(50) NOT NULL,
`login` varchar(50) NOT NULL,
`password` varchar(50) NOT NULL,
`avatar` varchar(50) NOT NULL,
CONSTRAINT `user_pk` PRIMARY KEY (`id`),
CONSTRAINT `user_idx_1` UNIQUE INDEX (`login`)
) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS `user_address` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`address_line_1` varchar(40) NOT NULL,
`address_line_2` varchar(40) NOT NULL,
`address_line_3` varchar(40) NOT NULL,
`address_line_4` varchar(40) NOT NULL,
`address_line_5` varchar(40) NOT NULL,
`postal_code` varchar(40) NOT NULL,
`city_name` varchar(40) NOT NULL,
`country_code` varchar(3) NOT NULL,
CONSTRAINT `user__address_pk` PRIMARY KEY (`id`),
INDEX `user_address_idx_1` (`user_id`),
INDEX `user_address_idx_2` (`country_code`),
CONSTRAINT `user_address_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`),
CONSTRAINT `user_address_ibfk_2` FOREIGN KEY (`country_code`) REFERENCES `country` (`alpha3`)
) ENGINE=InnoDB;
ALTER TABLE `user`
ADD COLUMN IF NOT EXISTS `shipping_address` int(11) NULL,
ADD COLUMN IF NOT EXISTS `billing_address` int(11) NULL,
ADD CONSTRAINT IF NOT EXISTS `user_ibfk_2` FOREIGN KEY (`shipping_address`) REFERENCES `user_address` (`id`)
ADD CONSTRAINT IF NOT EXISTS `user_ibfk_3` FOREIGN KEY (`billing_address`) REFERENCES `user_address` (`id`);
CREATE INDEX IF NOT EXISTS `user_idx_2` ON `user`(`shipping_address`);
CREATE INDEX IF NOT EXISTS `user_idx_3` ON `user`(`billing_address`);
CREATE TABLE IF NOT EXISTS `product_types` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`type` varchar(50) NOT NULL,
`description` varchar(4000) DEFAULT NULL,
CONSTRAINT `product_types_pk` PRIMARY KEY (`id`),
CONSTRAINT `product_types_idx_1` UNIQUE INDEX (`type`)
) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS `products` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`code` varchar(15) NOT NULL,
`name` varchar(70) NOT NULL,
`type` int(11) NOT NULL,
`scale` varchar(10) NOT NULL,
`vendor` varchar(50) NOT NULL,
`description` text NOT NULL,
`stock_level` smallint(6) NOT NULL,
`cost` decimal(10,2) NOT NULL,
`price` decimal(10,2) NOT NULL,
CONSTRAINT `product_pk` PRIMARY KEY (`id`),
INDEX `product_idx_2` (`type`),
CONSTRAINT `product_idx_1` UNIQUE INDEX (`code`),
CONSTRAINT `products_ibfk_1` FOREIGN KEY (`type`) REFERENCES `product_types` (`id`)
) ENGINE=InnoDB;
ALTER TABLE `products` ADD FULLTEXT(`description`);
CREATE TABLE IF NOT EXISTS `orders` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`order_date` timestamp NOT NULL DEFAULT current_timestamp(),
`shipped_date` timestamp DEFAULT NULL,
`status` varchar(15) NOT NULL,
`customer_id` int(11) NOT NULL,
CONSTRAINT `order_pk` PRIMARY KEY (`id`),
INDEX `order_idx_1` (`customer_id`),
CONSTRAINT `orders_ibfk_1` FOREIGN KEY (`customer_id`) REFERENCES `user` (`id`)
) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS `order_lines` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`order_id` int(11) NOT NULL,
`product_id` int(11) NOT NULL,
`quantity` smallint(6) NOT NULL,
`cost` decimal(10,2) NOT NULL,
`price` decimal(10,2) NOT NULL,
CONSTRAINT `order_lines_pk` PRIMARY KEY (`id`),
INDEX `order_lines_idx_1` (`order_id`),
CONSTRAINT `order_lines_idx_2` UNIQUE INDEX (`product_id`),
CONSTRAINT `order_lines_ibfk_1` FOREIGN KEY (`order_id`) REFERENCES `orders` (`id`),
CONSTRAINT `order_lines_ibfk_2` FOREIGN KEY (`product_id`) REFERENCES `products` (`id`)
) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS `order_address` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`order_id` int(11) NOT NULL,
`type` ENUM ('SHIPPING', 'BILLING'),
`address_line_1` varchar(40) NOT NULL,
`address_line_2` varchar(40) NOT NULL,
`address_line_3` varchar(40) NOT NULL,
`address_line_4` varchar(40) NOT NULL,
`address_line_5` varchar(40) NOT NULL,
`postal_code` varchar(40) NOT NULL,
`city_name` varchar(40) NOT NULL,
`country_code` varchar(3) NOT NULL,
CONSTRAINT `order_address_pk` PRIMARY KEY (`id`),
INDEX `order_address_idx_1` (`user_id`),
INDEX `order_address_idx_2` (`country_code`),
CONSTRAINT `order_address_ibfk_1` FOREIGN KEY (`order_id`) REFERENCES `orders` (`id`),
CONSTRAINT `order_address_ibfk_2` FOREIGN KEY (`country_code`) REFERENCES `country` (`alpha3`)
) ENGINE=InnoDB;
_________________________
ERROR
Static analysis:
1 errors were found during analysis.
Missing comma before start of a new alter operation. (near "ADD" at position 255)
SQL query:
ALTER TABLE `user`
ADD COLUMN IF NOT EXISTS `shipping_address` int(11) NULL,
ADD COLUMN IF NOT EXISTS `billing_address` int(11) NULL,
ADD CONSTRAINT IF NOT EXISTS `user_ibfk_2` FOREIGN KEY (`shipping_address`) REFERENCES `user_address` (`id`)
ADD CONSTRAINT IF NOT EXISTS `user_ibfk_3` FOREIGN KEY (`billing_address`) REFERENCES `user_address` (`id`)
MySQL said: Documentation
#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 'FOREIGN KEY (`shipping_address`) REFERENCES `user_address` (`id`) ADD CONS...' at line 4
You don't have a comma separating your last two lines of SQL.
Please use this:
ALTER TABLE `user`
ADD COLUMN IF NOT EXISTS `shipping_address` int(11) NULL,
ADD COLUMN IF NOT EXISTS `billing_address` int(11) NULL,
ADD CONSTRAINT IF NOT EXISTS `user_ibfk_2` FOREIGN KEY (`shipping_address`) REFERENCES `user_address` (`id`),
ADD CONSTRAINT IF NOT EXISTS `user_ibfk_3` FOREIGN KEY (`billing_address`) REFERENCES `user_address` (`id`)
SQL will separate the interests of different statements with the Comma, This works similar to a Javascript Semi colon

How to fix 'MySQL Error: 1822. Missing index for contraint' On creating a composite foreign key

I'm trying to create a table with a composite foreign key, but keep getting met with the error Error Code: 1822. Failed to add the foreign key constraint. Missing index for constraint 'fk_contractdateshistoric_contractdates_multiple' in the referenced table 'contractdates'
I'm using MySQL v8.0.16
I've checked if the column types are different, and I'm not sure what else could be the problem.
Here are the tables that make up the problem, All tables are made happily but the last one that contains the composite key causes the problem.
CREATE TABLE `contracts` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`Name` varchar(100) DEFAULT NULL,
`CreationDate` datetime DEFAULT NULL,
`CreatedBy` varchar(30) DEFAULT NULL,
`CompletionDate` date DEFAULT NULL,
`Comments` varchar(100) DEFAULT NULL,
PRIMARY KEY (`ID`)
);
CREATE TABLE `fieldheading` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`fieldTypeID` int(11) DEFAULT NULL,
`fieldCode` int(11) DEFAULT NULL,
`fieldHeading` varchar(100) DEFAULT NULL,
PRIMARY KEY (`ID`)
);
CREATE TABLE `contractdates` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`DateValue` datetime DEFAULT NULL,
`ContractID` int(11) NOT NULL,
`FieldHeadingID` int(11) NOT NULL,
PRIMARY KEY (`ID`),
UNIQUE KEY `uq_contractdates_contractID_FieldHeading_ID` (`ContractID`,`FieldHeadingID`),
KEY `fk_contractdates_contracts_id_idx` (`ContractID`),
KEY `fk_contractdates_fieldheading_id_idx` (`FieldHeadingID`),
CONSTRAINT `fk_contractdates_fieldheading_id` FOREIGN KEY (`FieldHeadingID`) REFERENCES `fieldheading` (`id`),
CONSTRAINT `fk_contractdates_contracts_id` FOREIGN KEY (`ContractID`) REFERENCES `contracts` (`id`)
) COMMENT='Table to hold the dates for a contract, one row is one date for a specific contract';
CREATE TABLE `contractdateshistoric` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`ContractID` int(11) NOT NULL,
`ContractDateCurrentID` int(11) NOT NULL,
`FieldHeadingID` int(11) NOT NULL,
`ChangedByID` int(11) NOT NULL,
`DateValue` datetime NOT NULL,
`TimeStampChanged` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`ID`),
KEY `fk_contractdateshistoric_contractdates_mutiple_idx` (`ContractID`, `FieldHeadingID`, `ContractDateCurrentID`),
CONSTRAINT `fk_contractdateshistoric_contractdates_multiple` FOREIGN KEY (`ContractID`, `FieldHeadingID`, `ContractDateCurrentID`) REFERENCES `contractdates` (`contractid`, `fieldheadingid`, `id`)
) COMMENT='Audit trail of the dates';
Since you are using Composite FK in the table contractdates try adding composite index as well
KEY `fk_contractdates_mutiple_idx` (`ContractID`,`FieldHeadingID`,`ID`)
Whole create statement
CREATE TABLE `contractdates` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`DateValue` datetime DEFAULT NULL,
`ContractID` int(11) NOT NULL,
`FieldHeadingID` int(11) NOT NULL,
PRIMARY KEY (`ID`),
KEY `fk_contractdates_contracts_id_idx` (`ContractID`),
KEY `fk_contractdates_fieldheading_id_idx` (`FieldHeadingID`),
KEY `fk_contractdates_mutiple_idx` (`ContractID`,`FieldHeadingID`,`ID`),
CONSTRAINT `fk_contractdates_fieldheading_id` FOREIGN KEY (`FieldHeadingID`) REFERENCES `fieldheading` (`id`),
CONSTRAINT `fk_contractdates_contracts_id` FOREIGN KEY (`ContractID`) REFERENCES `contracts` (`id`)
) COMMENT='Table to hold the dates for a contract, one row is one date for a specific contract';
It's trying to tell you "you haven't created a necessary unique index on contractdates, that covers the columns (contractid, fieldheadingid, id) so I cannot create a foreign key on contractdateshistoric that refers to this set of columns when determining the single parent row"
I'm not sure why you're creating an fk that references 3 columns when contractdates has a pk that is just the ID column.
If a contractdateshistoric records refers to a single contractdates record as its parent, the historic record should have a contractdateid column that refers to contractdates.id - no need for multiple columns. Copy the pattern you used to relate a contractdates to its parent contract, and you'll be fine
I have tried by creating the keys individually for the columns, Please find the updated query:
CREATE TABLE `contractdateshistoric` (
`ID` INT(11) NOT NULL AUTO_INCREMENT,
`ContractID` INT(11) NOT NULL,
`ContractDateCurrentID` INT(11) NOT NULL,
`FieldHeadingID` INT(11) NOT NULL,
`ChangedByID` INT(11) NOT NULL,
`DateValue` DATETIME NOT NULL,
`TimeStampChanged` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`ID`),
KEY `fk_contractdateshistoric_contractdates_mutiple_idx` (`ContractID`),
KEY `fk_contractdateshistoric_contractdates_mutiple_idx1` (`FieldHeadingID`),
KEY `fk_contractdateshistoric_contractdates_mutiple_idx2` (`ContractDateCurrentID`),
CONSTRAINT `fk_contractdateshistoric_contractdates_multiple` FOREIGN KEY (`ContractID`)
REFERENCES `contractdates` (`contractid`),
CONSTRAINT `fk_contractdateshistoric_contractdates_multiple1` FOREIGN KEY (`FieldHeadingID`)
REFERENCES `contractdates` (`fieldheadingid`),
CONSTRAINT `fk_contractdateshistoric_contractdates_multiple2` FOREIGN KEY (`ContractDateCurrentID`)
REFERENCES `contractdates` (`id`)
);
It works fine.

not able to apply foreign key constraint in mysql

I can run the below query and there are no nulls in the user_id column in the result -
select c.*,r.user_id from chat_group_users c left join roleuser r
on c.user_id = r.user_id;
But I cannot apply the foreign key constraint and mysql just says
Error Code: 1215. Cannot add foreign key constraint
The command i wrote -
ALTER TABLE chat_group_users
ADD CONSTRAINT fk_roleuser FOREIGN KEY (user_id) REFERENCES roleuser (user_id)
ON DELETE cascade ON UPDATE cascade;
The table structures -
CREATE TABLE `roleuser` (
`User_ID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`UserNM` varchar(50) NOT NULL,
`UserPS` varchar(150) NOT NULL,
`r_username` varchar(50) DEFAULT NULL,
`UGroup` varchar(5) NOT NULL DEFAULT 'Usar',
`FirstName` varchar(45) NOT NULL,
`LastName` varchar(45) NOT NULL,
PRIMARY KEY (`User_ID`),
UNIQUE KEY `Index_2` (`UserNM`),
) ENGINE=InnoDB AUTO_INCREMENT=50 DEFAULT CHARSET=latin1;
CREATE TABLE `chat_group_users` (
`auto_id` int(11) NOT NULL AUTO_INCREMENT,
`group_id` int(11) DEFAULT NULL,
`user_id` int(10) DEFAULT NULL,
`is_admin` varchar(5) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
PRIMARY KEY (`auto_id`),
UNIQUE KEY `unique_user_group` (`user_id`,`group_id`),
KEY `fc_group_id` (`group_id`),
CONSTRAINT `fc_group_id` FOREIGN KEY (`group_id`)
REFERENCES `chat_group`(`auto_id`)
ON DELETE CASCADE ON UPDATE CASCADE
)ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
missed the unsigned on the chat_group_users -
`User_ID` int(10) unsigned NOT NULL AUTO_INCREMENT, ...

Mysql innerjoin very slow

I have an SQL query that takes over 4 hours to complete.
The query is as follows
UPDATE carepathaction a1
INNER JOIN carepathaction a2
ON a1.sourceoid = a2.oid
INNER JOIN carepathgroup g
ON g.sourceoid = a2.carepathgroupoid
INNER JOIN carepathphase f
ON f.oid = g.carepathphaseoid
SET a1.carepathgroupoid = g.oid
WHERE f.code = 'EDIT'
He has to update 65000 items. Is there some optimalization i can do in this query?
CarePathAction
CREATE TABLE `carepathaction`
(
`oid` INT(11) NOT NULL,
`typeid` CHAR(1) NOT NULL DEFAULT 'X',
`sequencenumber` INT(11) NOT NULL,
`description` VARCHAR(1024) NOT NULL,
`duration` INT(11) NOT NULL comment 'In minutes',
`deadline` INT(11) NOT NULL comment
'# dagen in combinatie met deadlineType (sinds begin traject of sinds begin deze actie)'
,
`deadlinetype` INT(11) NOT NULL comment
'1) = deadline sinds zorgpad\n2) = deadline sinds start deze actie\n3) = deadline sinds zorgpadfase'
,
`repeatperweek` INT(11) DEFAULT NULL,
`numbertorepeat` INT(11) DEFAULT NULL,
`carepathoid` INT(11) DEFAULT NULL,
`usertaskoid` INT(11) DEFAULT NULL,
`templateattachment` VARCHAR(45) DEFAULT NULL,
`partyrolecategoryoid` INT(11) DEFAULT NULL,
`automatic` BIT(1) NOT NULL DEFAULT b'0',
`carepathphaseoid` INT(11) DEFAULT NULL,
`parentoid` INT(11) DEFAULT NULL,
`documentoid` INT(11) DEFAULT NULL,
`epdtemplateoid` INT(11) DEFAULT NULL,
`producttypeoid` INT(11) DEFAULT NULL,
`evaluateby` INT(11) DEFAULT NULL,
`pathlock` BIT(1) NOT NULL DEFAULT b'0',
`carepathgroupoid` INT(11) NOT NULL,
`activitygroupoid` INT(11) DEFAULT NULL,
`title` VARCHAR(45) DEFAULT NULL,
`carepathactionswitchtype` INT(11) DEFAULT NULL,
`modulesdomaincode` VARCHAR(10) DEFAULT NULL,
`startday` INT(11) NOT NULL DEFAULT '0',
`sourceoid` INT(11) DEFAULT NULL,
`templatefilename` VARCHAR(100) DEFAULT NULL,
`istask` BIT(1) NOT NULL DEFAULT b'0',
`typecontact` INT(11) DEFAULT NULL,
`carepathactionepdoid` INT(11) DEFAULT NULL,
`carepathactiontreatmentplanoid` INT(11) DEFAULT NULL,
`clientportalenabled` BIT(1) DEFAULT NULL,
`startafternumberofdaysepddatefield` INT(11) DEFAULT NULL,
`startafterdateepdfieldoid` INT(11) DEFAULT NULL,
`epdtemplatefieldoid` INT(11) DEFAULT NULL,
PRIMARY KEY (`oid`),
KEY `carepathactionfk1_idx` (`carepathoid`),
KEY `carepathactionfk2_idx` (`carepathphaseoid`),
KEY `carepathactionfk3_idx` (`documentoid`),
KEY `carepathactionfk4_idx` (`epdtemplateoid`),
KEY `carepathactionfk5_idx` (`producttypeoid`),
KEY `carepathactionfk6_idx` (`carepathgroupoid`),
KEY `carepathactionfk6_idx1` (`activitygroupoid`),
KEY `carepathactionfk7_idx` (`parentoid`),
KEY `carepathactionfk8_idx` (`usertaskoid`),
KEY `carepathactionfk10_idx` (`partyrolecategoryoid`),
KEY `carepathactionfk11_idx` (`carepathactionepdoid`),
KEY `carepathactionfk12_idx` (`carepathactiontreatmentplanoid`),
KEY `carepathactionfk13_idx` (`startafterdateepdfieldoid`),
KEY `carepathactionfk14_idx` (`epdtemplatefieldoid`),
CONSTRAINT `carepathactionfk14` FOREIGN KEY (`epdtemplatefieldoid`)
REFERENCES `epdtemplatefield` (`oid`) ON DELETE no action ON UPDATE no
action,
CONSTRAINT `carepathactionfk1` FOREIGN KEY (`carepathoid`) REFERENCES
`carepath` (`oid`) ON DELETE no action ON UPDATE no action,
CONSTRAINT `carepathactionfk10` FOREIGN KEY (`partyrolecategoryoid`)
REFERENCES `partyrolecategory` (`oid`) ON DELETE no action ON UPDATE no
action,
CONSTRAINT `carepathactionfk11` FOREIGN KEY (`carepathactionepdoid`)
REFERENCES `carepathaction` (`oid`) ON DELETE no action ON UPDATE no action
,
CONSTRAINT `carepathactionfk12` FOREIGN KEY (
`carepathactiontreatmentplanoid`) REFERENCES `carepathaction` (`oid`) ON
DELETE no action ON UPDATE no action,
CONSTRAINT `carepathactionfk13` FOREIGN KEY (`startafterdateepdfieldoid`)
REFERENCES `carepathaction` (`oid`) ON DELETE no action ON UPDATE no action
,
CONSTRAINT `carepathactionfk2` FOREIGN KEY (`carepathphaseoid`) REFERENCES
`carepathphase` (`oid`) ON DELETE no action ON UPDATE no action,
CONSTRAINT `carepathactionfk3` FOREIGN KEY (`documentoid`) REFERENCES
`document` (`oid`) ON DELETE no action ON UPDATE no action,
CONSTRAINT `carepathactionfk4` FOREIGN KEY (`epdtemplateoid`) REFERENCES
`epdtemplate` (`oid`) ON DELETE no action ON UPDATE no action,
CONSTRAINT `carepathactionfk5` FOREIGN KEY (`producttypeoid`) REFERENCES
`producttype` (`oid`) ON DELETE no action ON UPDATE no action,
CONSTRAINT `carepathactionfk6` FOREIGN KEY (`carepathgroupoid`) REFERENCES
`carepathgroup` (`oid`) ON DELETE no action ON UPDATE no action,
CONSTRAINT `carepathactionfk7` FOREIGN KEY (`parentoid`) REFERENCES
`carepathaction` (`oid`) ON DELETE no action ON UPDATE no action,
CONSTRAINT `carepathactionfk8` FOREIGN KEY (`usertaskoid`) REFERENCES
`tasktoschedule` (`oid`) ON DELETE no action ON UPDATE no action
)
CarePathGroup
CREATE TABLE `carepathgroup`
(
`oid` INT(11) NOT NULL,
`sequencenumber` INT(11) NOT NULL,
`title` VARCHAR(50) NOT NULL,
`carepathoid` INT(11) DEFAULT NULL,
`carepathphaseoid` INT(11) NOT NULL,
`sourceoid` INT(11) DEFAULT NULL,
PRIMARY KEY (`oid`),
KEY `carepathgroupfk1_idx` (`carepathoid`),
KEY `carepathgroupfk2_idx` (`carepathphaseoid`),
CONSTRAINT `carepathgroupfk2` FOREIGN KEY (`carepathphaseoid`) REFERENCES
`carepathphase` (`oid`) ON DELETE no action ON UPDATE no action
)
CarePathPhase
CREATE TABLE `carepathphase`
(
`oid` INT(11) NOT NULL,
`code` VARCHAR(6) NOT NULL,
`description` VARCHAR(45) NOT NULL,
`sequencenumber` INT(11) NOT NULL DEFAULT '0',
`carepathoid` INT(11) DEFAULT NULL,
`carepathphasetype` INT(11) NOT NULL DEFAULT '0',
`sourceoid` INT(11) DEFAULT NULL,
PRIMARY KEY (`oid`),
KEY `carepathphasefk1_idx` (`carepathoid`),
CONSTRAINT `carepathphasefk1` FOREIGN KEY (`carepathoid`) REFERENCES
`carepath` (`oid`) ON DELETE no action ON UPDATE no action
)
explain
1 SIMPLE f ALL PRIMARY 61925 Using where
1 SIMPLE g ref CarePathGroupFK2_idx CarePathGroupFK2_idx 4 amis.f.Oid 1
1 SIMPLE a1 ALL 166582 Using join buffer
1 SIMPLE a2 eq_ref PRIMARY,CarePathActionFK6_idx PRIMARY 4 amis.a1.SourceOid 1 Using where
There are two ALL join types in the explain, these are the ones you need to focus (for details see mysql documentation on explain output).
The create table statements show that:
You do not have index on the carepathphase.code field, which is used in the where criteria, so you should rectify that.
There is no index on carepathaction.sourceoid, which is used in the join, so you should create one there. You may try to create a combined index on oid, sourceoid fields (or the other way around) because mysql may be able to use the combined index to match the rows.
Run explain on the select (if you have mysql v5.6 or newer, then you can run it directly on the update) after adding the indexes and see, if the ALLs change. The 2nd all next to a2 seems to be the real critical stuff to me.

Error 1050 when trying to add foreign key constraing in MySQL

I have tried adding a column to my UserOrder table called discountcode. This is a nullable foreign key into
alter table UserOrder add column discountCode varchar(100) null;
alter table UserOrder add foreign key FK_UserOrder_DiscountCode_code(`discountCode`) references DiscountCode(`code`);
The error happens on the second line. Both tables are running InnoDB. I am on MySQL 5.5.11.
Here is the error log...
[2012-05-29 23:59:07] [42S01][1050] Table '.\realtorprint_dev_dev\userorder' already exists
[2012-05-29 23:59:07] [HY000][1025] Error on rename of '.\realtorprint_dev_dev\#sql-28a4_3' to '.\realtorprint_dev_dev\userorder' (errno: -1)
[2012-05-29 23:59:07] [42S01][1050] Table '.\realtorprint_dev_dev\userorder' already exists
Here is "show create Table UserOrder"
'CREATE TABLE `userorder` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`created` datetime NOT NULL,
`paymentTxID` varchar(255) DEFAULT NULL,
`shippedDate` datetime DEFAULT NULL,
`shippingTrackingNumber` varchar(255) DEFAULT NULL,
`taxType` varchar(255) NOT NULL,
`taxValue` decimal(10,2) NOT NULL,
`orderStatus` varchar(50) NOT NULL,
`user_id` bigint(20) NOT NULL,
`address` varchar(255) NOT NULL,
`city` varchar(255) NOT NULL,
`country` varchar(255) NOT NULL,
`stateProvince` varchar(255) NOT NULL,
`zipPostal` varchar(255) NOT NULL,
`paymentType` varchar(255) NOT NULL,
`backendUserId` bigint(20) DEFAULT NULL,
`adjustedTotalPrice` decimal(10,2) DEFAULT NULL,
`adjustedPrinterPrice` decimal(10,2) DEFAULT NULL,
`adminNotes` varchar(2048) DEFAULT NULL,
`printerBillStatus` varchar(40) NOT NULL,
`userInvoiceStatus` varchar(40) NOT NULL,
`expeditedAddressDescription` varchar(255) DEFAULT NULL,
`shippingType` varchar(50) NOT NULL,
`shippingCost` decimal(10,2) NOT NULL,
`discountCode` varchar(100) DEFAULT NULL,
`discountAmount` decimal(10,2) NOT NULL,
PRIMARY KEY (`id`),
KEY `idx_UserOrder_user_id` (`user_id`),
KEY `idx_UserOrder_orderStatus_id` (`orderStatus`),
KEY `FK_UserOrder_PaymentType` (`paymentType`),
KEY `FK_UserOrder_PrinterBillStatus_Name` (`printerBillStatus`),
KEY `FK_UserOrder_UserInvoiceStatus_Name` (`userInvoiceStatus`),
KEY `FK_UserOrder_User` (`backendUserId`),
KEY `FK_UserOrder_ShippingType_name` (`shippingType`),
CONSTRAINT `FK_UserOrderBcknd_User` FOREIGN KEY (`backendUserId`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `FK_UserOrder_user_id` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`),
CONSTRAINT `userorder_ibfk_1` FOREIGN KEY (`shippingType`) REFERENCES `shippingtype` (`name`),
CONSTRAINT `UserOrder_ibfk_2` FOREIGN KEY (`paymentType`) REFERENCES `paymenttype` (`name`),
CONSTRAINT `UserOrder_ibfk_6` FOREIGN KEY (`printerBillStatus`) REFERENCES `printerbillstatus` (`name`),
CONSTRAINT `UserOrder_ibfk_7` FOREIGN KEY (`userInvoiceStatus`) REFERENCES `userinvoicestatus` (`name`),
CONSTRAINT `UserOrder_ibfk_8` FOREIGN KEY (`orderStatus`) REFERENCES `orderstatus` (`name`)
) ENGINE=InnoDB AUTO_INCREMENT=21412 DEFAULT CHARSET=utf8'
Here is show create table DiscountCode...
'CREATE TABLE `discountcode` (
`code` varchar(100) NOT NULL,
`percent` int(11) NOT NULL,
`created` datetime NOT NULL,
`expires` datetime NOT NULL,
`maxUses` int(11) NOT NULL,
`useCount` int(11) NOT NULL,
PRIMARY KEY (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8'
As stated in the manual:
InnoDB requires indexes on foreign keys and referenced keys so that foreign key checks can be fast and not require a table scan. In the referencing table, there must be an index where the foreign key columns are listed as the first columns in the same order. Such an index is created on the referencing table automatically if it does not exist. This index might be silently dropped later, if you create another index that can be used to enforce the foreign key constraint. index_name, if given, is used as described previously.
Have you defined an index on the referenced key DiscountCode.code?