SCENARIO:
=========
Please consider this contrived relationship
Part ||---0< XOrderPart <0---|| Order
CREATE TABLE Order (
Order_ID INT NOT NULL AUTO_INCREMENT,
OrderDate Date NOT NULL,
PRIMARY KEY (Order_ID)
) ENGINE=INNODB AUTO_INCREMENT= 3 CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE TABLE Part (
Part_ID INT NOT NULL AUTO_INCREMENT,
UnitCost FLOAT NOT NULL,
PRIMARY KEY (Part_ID)
) ENGINE=INNODB AUTO_INCREMENT= 3 CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE TABLE XOrderPart (
Order_ID INT NOT NULL,
Part_ID INT NOT NULL,
PRIMARY KEY (Order_ID, Part_ID)
FOREIGN KEY(Order_ID) REFERENCES Order(Order_ID);
FOREIGN KEY(Part_ID) REFERENCES Part(Part_ID);
) ENGINE=INNODB AUTO_INCREMENT= 3 CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
PROBLEM:
=========
I want to use the last inserted ID from table Order and the max ID from Part as input parameters into table XOrderPart.
But mySQL throws error when I tried to access LAST_INSERT_ID() and MAX(Part_ID) in the same transaction block:
BEGIN
SET AUTOCOMMIT=0;
START TRANSACTION;
INSERT INTO Order (Customer_ID, OrderDate) VALUES (custId, ordDate);
@newOrderId = SELECT LAST_INSERT_ID(); // mySQL expects END here
@maxPartId = SELECT MAX(Part_ID) FROM Part; // mySQL expects END here
INSERT INTO XOrderPart(Customer_ID, Part_ID) VALUES (@newOrderId, @maxPartId);
COMMIT;
END
I need all inserts to complete successfully or rollback everything with an error message.
QUESTIONS:
===========
(111) How do I get hold of LAST_INSERT_ID from Order to use as an input parameter in XOrders_Parts?
(222) If the first insert fails, will the transaction crash because the next insert violates foreign key constraints?
Apologies bothering you guys constantly. :)