Rule, update and aggregate functions - Mailing list pgsql-general

From pgsql-user
Subject Rule, update and aggregate functions
Date
Msg-id 20070202205607.467595846@mail.vunet.de
Whole thread Raw
Responses Re: Rule, update and aggregate functions
Re: Rule, update and aggregate functions
List pgsql-general
Hi,

I got stuck with the following problem and strangely couldn't find
anything similar in the list:

Assume two tables:
table: warehouse, columns: id, incoming, outgoing
table: articles, columns: id, articles_in_stock

All I want is to create a rule, that everytime when articles leave or
get in the warehouse, the sum of articles is updated in articles database.

Tried :

CREATE RULE upd_articles AS ON UPDATE TO warehouse
DO ALSO UPDATE articles SET articles_in_stock =SUM(NEW.incoming)-SUM
(NEW.outgoing)
 WHERE articles.id=OLD.id;

All I get is a "aggregate functions not allowed on update".

So I tried to wrap it in a SELECT:

CREATE RULE upd_articles AS ON UPDATE TO warehouse
DO ALSO UPDATE articles SET articles_in_stock =(SELECT SUM(NEW.incoming)-
SUM(NEW.outgoing)
FROM warehouse WHERE NEW.id=OLD.id)
 WHERE articles.id=OLD.id;

with the same result.

What is the right way to achieve my goal? Or are rules the wrong
instrument for it?

Any help is kindly appreciated,
Thanks, Sebastian


pgsql-general by date:

Previous
From: "Boguk Maxim"
Date:
Subject: Some issues with planner and query optimization
Next
From: Bruno Wolff III
Date:
Subject: Re: Defining and Using variables in a postgres function