-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTriggers.sql
65 lines (52 loc) · 1.6 KB
/
Triggers.sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
DELIMITER //
CREATE TRIGGER update_total_items
AFTER INSERT ON order_items
FOR EACH ROW
BEGIN
-- Update the total_items in the orders table after a new item is inserted
UPDATE orders
SET total_items = total_items + NEW.quantity
WHERE id = NEW.order_id;
END //
DELIMITER ;
-- ====================================================================================
DELIMITER //
CREATE TRIGGER update_total_price
AFTER INSERT ON order_items
FOR EACH ROW
BEGIN
-- Update the total_price in the orders table after a new item is inserted
UPDATE orders
SET total_price = (
SELECT SUM(price * quantity)
FROM order_items
WHERE order_id = NEW.order_id
)
WHERE id = NEW.order_id;
END //
DELIMITER ;
-- ====================================================================================
DROP TRIGGER IF EXISTS update_total_items;
-- ====================================================================================
DELIMITER //
CREATE TRIGGER update_total_price_and_items
AFTER INSERT ON order_items
FOR EACH ROW
BEGIN
-- Update total_price in the orders table
UPDATE orders
SET total_price = (
SELECT SUM(price * quantity)
FROM order_items
WHERE order_id = NEW.order_id
),
-- Update total_items in the orders table
total_items = (
SELECT SUM(quantity)
FROM order_items
WHERE order_id = NEW.order_id
)
WHERE id = NEW.order_id;
END //
DELIMITER ;
-- ====================================================================================