简体   繁体   English

postgres function for 循环

[英]postgres function for loop

I have an orders table and an order_products_items table.我有一个orders表和一个order_products_items表。 The order_products_items has these fields: order_products_items具有以下字段:

  • order_id order_id
  • product_id产品编号
  • quantity数量
  • price价格

I am trying to create a calculated_field: calculated_total_products_price in the orders table through a before insert trigger function that would calculate the total order price by looping through all the order_products_items related to the order and multiplying the quantity with the price for every order item.我正在尝试通过before insert trigger function 在orders表中创建一个 calculated_field: calculated_total_products_price ,它将通过遍历与订单相关的所有order_products_items并将数量乘以每个订单商品的价格来计算总订单价格。

This is my failed attempt in doing so:这是我这样做的失败尝试:

CREATE OR REPLACE FUNCTION public.fn_trigger_total_order_price()
 RETURNS trigger
 LANGUAGE plpgsql
AS $function$
declare total float := 0.0;
        product record;
  BEGIN
    FOR product IN
      SELECT itm.price, itm.quantity
      FROM order_products_items itm
        INNER JOIN orders ord
        ON itm.order_id  = ord.id
      WHERE ord.id = NEW.id
        LOOP
            total = total + (product.price * product.quantity);
        END LOOP;

      NEW.calculated_total_products_price := total;
      RETURN NEW;
  END;
  $function$
;

The trigger looks like this:触发器看起来像这样:

CREATE TRIGGER fn_trigger_total_order_price BEFORE INSERT ON public.orders
  FOR EACH ROW EXECUTE PROCEDURE fn_trigger_total_order_price();

Somehow, I do not get any errors, but always get 0 as a result.不知何故,我没有得到任何错误,但结果总是得到 0。

Am I missing something?我错过了什么吗? or is there a better/more efficient way of approaching this?还是有更好/更有效的方法来解决这个问题?

Many thanks.非常感谢。

You don't need a loop in postgres to achieve this.您不需要 postgres 中的循环来实现此目的。

A simple AGGREGATION query would do.一个简单的聚合查询就可以了。

Something like就像是

SELECT SUM(quantity * price) 
FROM order_products_items
WHERE order_id = NEW.id

You also don't really need to mess with a trigger if you don't want to.如果你不想的话,你也真的不需要弄乱触发器。

Just make a view out of the query below and relate it to the orders table as something like order_totals只需查看下面的查询并将其与orders表相关联,如order_totals

SELECT order_id, SUM(quantity * price) order_total
FROM order_products_items
GROUP BY order_id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM