MySQL trigger insert after insert into another table - mysql
I want to add a foreign key into tblprowareinventory whenever I insert into tblprowareproducts:
tblProwareproducts
CREATE TABLE `tblprowareproducts` (
`ItemID` int(11) NOT NULL,
`ItemCode` varchar(30) NOT NULL,
`itemDescription` varchar(60) NOT NULL,
`Strand` varchar(30) NOT NULL,
`UnitCost` double NOT NULL,
`SaleCost` double NOT NULL,
`CategoryID_fk` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `tblprowareproducts`
ADD PRIMARY KEY (`ItemID`),
ADD KEY `CategoryID_fk` (`CategoryID_fk`);
ALTER TABLE `tblprowareproducts`
MODIFY `ItemID` int(11) NOT NULL AUTO_INCREMENT;
ALTER TABLE `tblprowareproducts`
ADD CONSTRAINT `tblprowareproducts_ibfk_1` FOREIGN KEY (`CategoryID_fk`) REFERENCES `tblprowarecategory` (`PCategoryID`) ON DELETE CASCADE ON UPDATE CASCADE;
COMMIT;
tblProwareinventory
CREATE TABLE `tblprowareinventory` (
`inventoryID` int(11) NOT NULL,
`ItemID_FK` int(11) NOT NULL,
`DateOfInventory` date NOT NULL,
`CurrentQuantity` int(11) NOT NULL,
`TotalQuantity` int(11) NOT NULL,
`DeliveredQuantity` int(11) NOT NULL,
`PhysicalCount` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `tblprowareinventory`
ADD PRIMARY KEY (`inventoryID`),
ADD KEY `ItemID_FK` (`ItemID_FK`);
ALTER TABLE `tblprowareinventory`
ADD CONSTRAINT `tblprowareinventory_ibfk_2` FOREIGN KEY (`ItemID_FK`) REFERENCES `tblprowareproducts` (`ItemID`) ON DELETE CASCADE ON UPDATE CASCADE;
COMMIT;
INSERT INTO tblprowareinventory(ItemID_FK)
VALUES ((SELECT ItemID FROM tblprowareproducts))
but I get this error:
You can use the following CREATE TRIGGER statement:
DELIMITER //
CREATE DEFINER = `root`#`localhost` TRIGGER AddToInventory AFTER INSERT ON tblprowareproducts
FOR EACH ROW
BEGIN
INSERT INTO tblprowareinventory (ItemID_FK) VALUES (NEW.ItemID);
END;//
DELIMITER ;
Note: You have to remove your current trigger on phpMyAdmin or with the following statement: DROP TRIGGER AddToInventory; to successfully run this CREATE TRIGGER statement.
The TRIGGER successfully add a new row to the tblprowareinventory table with the NEW.ItemID, but you defined a PRIMARY KEY on the inventoryID of tblprowareinventory table. That's OK, but after trying INSERT a second row on tblprowareinventory table, you should get an error:
#1062 - Duplicate entry '0' for key 'PRIMARY'
The TRIGGER tries to INSERT a second row on tblprowareinventory table with 0 on the inventoryID column. This is not possible because 0 can only exists once on the inventoryID column.
You can solve this issue using a AUTO_INCREMENT on the inventoryID column too:
ALTER TABLE `tblprowareinventory` MODIFY `inventoryID` INT(11) NOT NULL AUTO_INCREMENT;
To INSERT a new row on tblprowareproducts table I used the following statement:
INSERT INTO `tblprowareproducts` (`ItemID`, `ItemCode`, `itemDescription`, `Strand`, `UnitCost`, `SaleCost`, `CategoryID_fk`)
VALUES (NULL, '111', '111', '111', '1', '1', '1')
Related
Foreign Key Failure #1452 MariaDB PhpMyAdmin Mysql
got a slight problem with my constraint I wanna add to my tables: so first at all my tables: DROP TABLE IF EXISTS `Sales`; CREATE TABLE IF NOT EXISTS `Sales` ( `ItemNo` int(11) NOT NULL, `Model` varchar(100) NOT NULL unique, `PurchasingPrice` decimal(11,2) NOT NULL, `ManufNo` int(11) Not Null, `LocNo` int(11) NOT NULL, `SuppNo` int(11) NOT NULL, `CatNo`int(11) NOT NULL, `UnitPrice`decimal (11,2), PRIMARY KEY (`ItemNo`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; INSERT INTO `Sales` (`ItemNo`, `Model`, `PurchasingPrice`,`ManufNo`, `LocNo`,`SuppNo`,`CatNo`,`Unitprice`) VALUES (1,'Tieflader 18t',6969.84,4,1,6,2,9582.56), (2,'Betonmischer-3m³',47829.00,3,2,3,3,82457.23), (3,'Lastenkran 800kg',4129.00,2,2,2,3,8466.43), (4,'Hubwagen,10m',9478.00,1,2,3,3,18457.84); DROP TABLE IF EXISTS `Rent`; CREATE TABLE IF NOT EXISTS `Rent` ( `ItemNo` int(11) NOT NULL, ( Different Number-Area like 1000+, very small project) `Model` varchar(100) NOT NULL unique, `PurchasingPrice` decimal(11,2) NOT NULL, `ManufNo` int(11) Not Null, `LocNo` int(11) NOT NULL, `SuppNo` int(11) NOT NULL, `CatNo`int(11) NOT NULL, `PricePerDay`decimal (11,2), `RentDateNo`int(11), `AdressNo` int(11), PRIMARY KEY (`ItemNo`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; INSERT INTO `RENT` (`ItemNo`, `Model`, `PurchasingPrice`,`ManufNo`, `LocNo`,`SuppNo`,`CatNo`,`PricePerDay`,`RentDateNo`,`AdressNo`) VALUES (1000,'Betonmischer 50l',123.45,4,1,6,2,42.56,2,1), (1001,'Winkelschleifer 800 Watt³',29.00,3,2,3,3,17.23,3,1), (1002,'Akkuschrauber 12V',129.00,2,2,2,3,16.43,1,2), (1003,'Akkuschrauber 18V',178.00,1,2,3,3,21.84,1,2); DROP TABLE IF EXISTS `Stock`; CREATE TABLE IF NOT EXISTS `Stock` ( `ItemNo` int(11) NOT NULL, `Min-Stock` int(11) Not Null, `Current-Stock` int(11) Not Null, `Max-Stock` int(11) Not Null, PRIMARY KEY (`ItemNo`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; INSERT INTO `Stock` (`ItemNo`,`Min-Stock`,`Current-Stock`,`Max-Stock`) VALUES (1000,0,1,1), (1001,0,1,1), (1002,0,0,1), (1003,0,1,1), (1,2,5,8), (2,1,2,2), (3,3,6,9), (4,1,3,4); When I try to add an constraint FK with: ALTER TABLE `Stock` ADD CONSTRAINT `sales_stock_fk` FOREIGN KEY (`ItemNo`) REFERENCES `sales`(`ItemNo`) ON DELETE RESTRICT ON UPDATE RESTRICT, ADD CONSTRAINT `rent_stock_fk` FOREIGN KEY (`ItemNo`) REFERENCES `rent`(`ItemNo`) ON DELETE RESTRICT ON UPDATE RESTRICT; it does Fail. When I delete all Numbers which aren't from the sales Table I can use this one: ALTER TABLE `Stock` ADD CONSTRAINT `sales_stock_fk` FOREIGN KEY (`ItemNo`) REFERENCES `sales`(`ItemNo`) ON DELETE RESTRICT ON UPDATE RESTRICT; and can also add new items in the sales table as wanted and the new in stock. But I can't add Stocks for rent items and also the combined Add Constraint with both tables at once don't work. I am not sure how to get it work that I can add my Items to the table. I always get the #1452 child table failure. Maybe someone can help me an know how to handle it. The result should be: I got to the table stock and hover over an ItemNo and when I click it I should be forwarded to table sales if ItemNo is from sales or rent if from rent. I am using Xampp phpmyadmin, MariaDB
So the error is Cannot add or update a child row: a foreign key constraint fails you should change values the Sales table on ItemNo change it before 1 to 1000 and more your value is INSERT INTO `Sales` (`ItemNo`, `Model`, `PurchasingPrice`,`ManufNo`, `LocNo`,`SuppNo`,`CatNo`,`Unitprice`) VALUES (1,'Tieflader 18t',6969.84,4,1,6,2,9582.56), (2,'Betonmischer-3m³',47829.00,3,2,3,3,82457.23), (3,'Lastenkran 800kg',4129.00,2,2,2,3,8466.43), (4,'Hubwagen,10m',9478.00,1,2,3,3,18457.84); Change it to : INSERT INTO `Sales` (`ItemNo`, `Model`, `PurchasingPrice`,`ManufNo`, `LocNo`,`SuppNo`,`CatNo`,`Unitprice`) VALUES (1000,'Tieflader 18t',6969.84,4,1,6,2,9582.56), (1001,'Betonmischer-3m³',47829.00,3,2,3,3,82457.23), (1002,'Lastenkran 800kg',4129.00,2,2,2,3,8466.43), (1003,'Hubwagen,10m',9478.00,1,2,3,3,18457.84);
To create a trigger that if I insert a row in child table with null foreign key ,It inserts a new row in parent table with that criteria and new id
This is factors table: CREATE TABLE `factors` ( `id` int(11) NOT NULL AUTO_INCREMENT, `price_sum` int(11) NOT NULL, `date` datetime DEFAULT NULL, PRIMARY KEY (`id`)) And this one is subfactors table: CREATE TABLE `subfactors` ( `id` int(11) NOT NULL AUTO_INCREMENT, `price` int(11) NOT NULL, `factor_id` int(11) NOT NULL, PRIMARY KEY (`id`), FOREIGN KEY subfactors(`factor_id`) REFERENCES factors(`id`)) I've tried this query but it says that I can't insert a row into a child table: DELIMITER // CREATE TRIGGER my_trigger AFTER INSERT ON subfactors FOR EACH ROW BEGIN IF NEW.factor_id=NULL THEN INSERT INTO factor(id,price_sum) VALUES(NEW.factor_id,NEW.price); END IF; END // Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails
Cannot insert into table with stored generated primary key
I cannot insert data in table with generated stored primary key. My table is: CREATE TABLE `living_complex` ( `id` bigint(32) GENERATED ALWAYS AS (`location_id`) STORED NOT NULL, `location_id` int(11) NOT NULL, `name` varchar(255) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `unq_living_complex_name` (`name`), KEY `idx_living_complex_location_id` (`location_id`), KEY `idx_living_complex_name` (`name`), CONSTRAINT `fk_living_complex_location_id` FOREIGN KEY (`location_id`) REFERENCES `location` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB DEFAULT CHARSET=utf8; My insert statement: INSERT INTO `reeve`.`living_complex` (`location_id`, `name`) VALUES ('1', 'some_living_complex'); Error is: 1048: Column 'id' cannot be null I don't have NOT NULL key-word in create statement. Why does it asks for id?
Got it. There was an mistake in trigger CREATE DEFINER=`root`#`localhost` TRIGGER `reeve`.`trg_living_complex_object_id` BEFORE INSERT ON `living_complex` FOR EACH ROW BEGIN INSERT INTO `reeve`.`object` ( `id`, `object_type_id` ) VALUES ( new.id, (SELECT `object_type`.`id` FROM `reeve`.`object_type` WHERE `table_name` = 'living_complex') ); END Which should be AFTER insert. Because I don't have NEW.id (generated by expression) until I do insert.
MySQL Update on duplicate error
I have two tables, EVENTS and EVENT_ATTENDEES. I'd like to be able to attempt a row insert on event_attendees and if the call_sign and event_id already exist in the table, it should update the response for that row instead of inserting a new one. Events Table CREATE TABLE `events` ( `event_id` int(11) NOT NULL, `created_by` varchar(1000) NOT NULL, `event_type` varchar(1000) NOT NULL, `event_name` varchar(1000) NOT NULL, `event_start` datetime NOT NULL, `event_end` datetime NOT NULL, `max_attendees` varchar(10) NOT NULL, `open_registration` varchar(10) NOT NULL ) ALTER TABLE `events` ADD PRIMARY KEY (`event_id`); ALTER TABLE `events` MODIFY `event_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=11 Event Attendees CREATE TABLE `event_attendees` ( `id` int(11) NOT NULL, `event_id` int(11) NOT NULL, `call_sign` varchar(10) NOT NULL, `response` varchar(10) NOT NULL ) ALTER TABLE `event_attendees` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `event_id_2` (`event_id`,`call_sign`), ADD KEY `event_id` (`event_id`) USING BTREE; ALTER TABLE `event_attendees` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=15; ALTER TABLE `event_attendees` ADD CONSTRAINT `event_id_fk` FOREIGN KEY (`event_id`) REFERENCES `events` (`event_id`) ON DELETE CASCADE ON UPDATE NO ACTION; I have tried the below query, but constantly get an error (I have created an event that has event_id = 10): INSERT INTO event_attendees (event_id, call_sign, response) VALUES ('10', '007', 'Declined') ON DUPLICATE KEY UPDATE response = VALUES('Declined') " #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 ''test')' at line 6"
There is no need of VALUES here. Modify your query as: INSERT INTO event_attendees (event_id, call_sign, response) VALUES ('10', '007', 'Declined') ON DUPLICATE KEY UPDATE response = 'Declined' From doc: you can use the VALUES(col_name) function to refer to column values from the INSERT portion of the INSERT ... ON DUPLICATE KEY UPDATE statement Here you can find more about VALUES function.
Mysql clone id with trigger
I have two tables: CREATE TABLE IF NOT EXISTS `users` ( `id` int(8) NOT NULL AUTO_INCREMENT, `username` varchar(45) NOT NULL, `password` varchar(200) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `username` (`username`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1; CREATE TABLE IF NOT EXISTS `users_info` ( `id` int(8) NOT NULL, `name` varchar(35) NOT NULL, `address` varchar(35) NOT NULL, PRIMARY KEY (`id`), ) ENGINE=MyISAM DEFAULT CHARSET=latin1; I want that when an user is inserted in table users, to automatically insert a new row in table users_info that would contain the same id in the id column, as the users table. When I do my inserts, I do them like this: INSERT INTO users (username,password) VALUES ('user1','pass1'); I believe that I should look at MySQL triggers. I did take a look but I don't know how to retrieve the key id from the users table for every last row that is inserted, supposing that other rows could be inserted in parallel in other threads.
If you create AFTER INSERT trigger, you can use NEW object: CREATE TRIGGER `aftInsert_users` AFTER INSERT ON `users` FOR EACH ROW BEGIN INSERT INTO users_info (itemID) VALUES (NEW.id); END;
A trigger on after insert should work if you define default values for the columns defined as not null: CREATE TRIGGER insert_users_info AFTER INSERT ON `users` FOR EACH ROW INSERT INTO `users_info` (id) VALUES (NEW.id); See the MySQL documentation on triggers for more information.