'Update Table from Trigger

I have the following tables in a database:

CREATE TABLE `CRUISE-RES` (
`cruiseid` INT,
`end-day` DATE,
`start-day` DATE
PRIMARY KEY (`cruiseid`)); 

CREATE TABLE `ROOM` (
`cruise-id` INT,
`price` FLOAT,
FOREIGN KEY (`cruise-id`));

CREATE TABLE `PROFIT` (
`cruiseid` INT,
`total` FLOAT);

With the following sample table inserts:

-- cruise table inserts
insert into `CRUISE-ID` (`cruiseid`,`start-day`,`end-day`)
values (1, '2022/01/01', '2022/01/05'), (1, '2022/01/05', '2022/01/10'), (2, '2022/01/05', '2022/01/10')

-- room table inserts
insert into ROOM (price,`cruise-id`)
values (5,1), (10,1), (25,2)

I also have the following function that shows the profit of each cruiseid based on the number of days in the CRUISE-RES * price per day.

SELECT c.`cruiseid`, sum(rm.`price`*(DATEDIFF(c.`end-date`, c.`start-date`))) AS 'total_profit'
FROM ROOM rm
JOIN `CRUISE-RES` c
ON rm.`cruise-id` = c.cruiseid
GROUP BY rm.`cruise-id`,'cruiseid'

How can I use this information on a trigger that updates the PROFIT table after each insert into CRUISE-RES table?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source