我想制作一个基于CUSTOMER_ID对TOTALCOST求和的触发器。并将数据插入MAIN_ORDER表。
表:ORDER_DETAIL
ID | CUSTOMER_ID | TOTALCOST
------------------------
1 | 1000 | 50
2 | 1000 | 50
3 | 2000 | 200
4 | 2000 | 200
表:MAIN_ORDER
CUSTOMER_ID | ORDER_PRICE
------------------------
1000 | 100
2000 | 400
我试过这个但是没有用
CREATE OR REPLACE TRIGGER MOVEDETAIL
BEFORE INSERT ON MAIN_ORDER FOR EACH ROW
BEGIN
SELECT ORDER_DETAIL.CUSTOMER_ID,ORDER_DETAIL.SUM(TOTALCOST)
INTO :NEW.CUSTOMER_ID,:NEW.ORDER_PRICE
FROM ORDER_DETAIL
GROUP BY CUSTOMER_ID;
END;
答案 0 :(得分:0)
不管你的触发器,如果我理解你有一个表ORDER_DETAIL
,你想保持第二个表(MAIN_ORDER
)的数据与ORDER_DETAIL
数据的每个修改保持一致,以便MAIN_ORDER
始终包含TOTALCOST
中每个CUSTOMER_ID
的{{1}}总和。
如果您想使用触发器执行此操作,则必须处理ORDER_DETAIL
上的所有修改,即您需要ORDER_DETAIL
,INSERT
,UPDATE
上的DELETE
触发器{1}}(不在ORDER_DETAIL
上)。
鉴于您只需要保持信息一致,我建议您创建一个视图,而不是使用触发器处理表。
例如:
MAIN_ORDER
视图始终显示正确的信息,不需要触发器
CREATE OR REPLACE VIEW V_MAIN_ORDER
AS SELECT CUSTOMER_ID,
SUM(TOTALCOST) AS ORDER_PRICE
FROM ORDER_DETAIL
GROUP BY CUSTOMER_ID
无论你在桌子上做什么
SQL> INSERT INTO ORDER_DETAIL( ID, CUSTOMER_ID, TOTALCOST) VALUES (1, 1000, 50);
1 row created.
SQL> INSERT INTO ORDER_DETAIL( ID, CUSTOMER_ID, TOTALCOST) VALUES (2, 1000, 50);
1 row created.
SQL> INSERT INTO ORDER_DETAIL( ID, CUSTOMER_ID, TOTALCOST) VALUES (3, 2000, 200);
1 row created.
SQL> INSERT INTO ORDER_DETAIL( ID, CUSTOMER_ID, TOTALCOST) VALUES (4, 2000, 200);
1 row created.
SQL> SELECT * FROM V_MAIN_ORDER;
CUSTOMER_ID ORDER_PRICE
----------- -----------
1000 100
2000 400