2009/10/29 Daniel Chiaramello <daniel(dot)chiaramello(at)golog(dot)net>:
> Never mind, I found how finally:
> qty = qty+s_count
> FROM (
> count(*) AS s_count
> GROUP BY
> ) AS summary
> summary.product_id = product.id
> Sorry for disturbance!
> Daniel Chiaramello a écrit :
>> I have a very basic question, relative to the following "problem".
>> I have the following tables:
>> I want to update the "qty" field of the "product" table by incrementing it
>> each time there is an order in the "orders" table, referencing a given
>> product through the "intermediate" table.
>> I tried the following request:
>> qty = qty+1
>> orders.intermediate_id=intermediate.id AND
>> But of course it does what was predictable - ie the qty "field" is
>> incremented only once, even if more than one entry is referencing a given
>> product. But it's not what I was hoping...
>> What would be the "good" solution to do that UPDATE?
>> Thanks for your attention!
>> Daniel Chiaramello
Your solution looks like it would perform a cumulative calculation.
Surely you'd want qty = s_count?
In any case, wouldn't you be better off not having a quantity column
at all and just calculate it with either a query or a view?
SELECT product.id, COUNT(intermediate.product_id)
LEFT JOIN intermediate ON product.id = intermediate.product_id
GROUP BY product.id
ORDER BY product.id
Or include a product name in the product table to get more meaningful
output. You'd then get an output like:
id name count
1 Orange 5
2 Apples 7
3 Pears 2
4 Kiwi 0
If you don't want ones for which there have been no orders for (or
whatever your intermediate table is for), use an INNER JOIN instead.
In response to
pgsql-general by date
|Next:||From: Sam Mason||Date: 2009-10-29 13:41:13|
|Subject: Re: multiple identical calc and function in single query|
|Previous:||From: Daniel Chiaramello||Date: 2009-10-29 11:57:31|
|Subject: Re: [Newbie] UPDATE based on other table content|