[英]how to make a trigger in sql with GROUP BY? (oracle database)
I want to make a trigger which sum the TOTALCOST based on the CUSTOMER_ID. 我想创建一个触发器,该触发器根据CUSTOMER_ID汇总TOTALCOST。 And insert the data to the MAIN_ORDER table.
并将数据插入到MAIN_ORDER表。
TABLE: ORDER_DETAIL 表格:ORDER_DETAIL
ID | CUSTOMER_ID | TOTALCOST
------------------------
1 | 1000 | 50
2 | 1000 | 50
3 | 2000 | 200
4 | 2000 | 200
TABLE: MAIN_ORDER 表格:MAIN_ORDER
CUSTOMER_ID | ORDER_PRICE
------------------------
1000 | 100
2000 | 400
I have tried this but it doesn't work 我已经尝试过了,但是没有用
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;
Keeping aside your trigger, if I understand well you have a table ORDER_DETAIL
and you want to keep the data of a second table ( MAIN_ORDER
) aligned with every modification on ORDER_DETAIL
data, so that MAIN_ORDER
always contains the sum of TOTALCOST
for each CUSTOMER_ID
in ORDER_DETAIL
. 抛开触发器,如果我很了解您有一个表
ORDER_DETAIL
并且您想使第二个表( MAIN_ORDER
)的数据与对ORDER_DETAIL
数据的每次修改保持一致,以便MAIN_ORDER
始终包含TOTALCOST
中每个CUSTOMER_ID
的ORDER_DETAIL
。
If you want to do so with triggers, you have to handle every modification on ORDER_DETAIL
, that is you need triggers for INSERT
, UPDATE
, DELETE
on ORDER_DETAIL
( not on MAIN_ORDER
). 如果要使用触发器,则必须处理对
ORDER_DETAIL
所有修改,即需要对ORDER_DETAIL
上的INSERT
, UPDATE
, DELETE
进行ORDER_DETAIL
(而不是对MAIN_ORDER
)。
Given that you only have to keep informations aligned, I would suggest creating a view instead of handling a table with triggers. 鉴于您只需要使信息保持一致,我建议您创建一个视图而不是使用触发器来处理表。
For example: 例如:
CREATE OR REPLACE VIEW V_MAIN_ORDER
AS SELECT CUSTOMER_ID,
SUM(TOTALCOST) AS ORDER_PRICE
FROM ORDER_DETAIL
GROUP BY CUSTOMER_ID
The view always shows correct informations, with no need for triggers 该视图始终显示正确的信息,而无需触发器
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
and no matter what you do on the table 不管你在桌上做什么
SQL> DELETE ORDER_DETAIL WHERE CUSTOMER_ID = 1000;
2 rows deleted.
SQL> SELECT * FROM V_MAIN_ORDER;
CUSTOMER_ID ORDER_PRICE
----------- -----------
2000 400
SQL>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.