This topic is locked

Updating a field with a Sum from another field

1/23/2008 12:07:57 PM
PHPRunner General questions
M
mrpeeble author

Hi Guys:
I have a one to many relationship between a ParentCost table and a ChildCost table.

I would like to update the field Cost3 in the parent table with the SUM of field Cost3 in the child table.
ParentCost

ID

Cost1

Cost2

Cost3
ChildCost

ChildID

ParentID

Cost3
I have the following update code that works fine for regular updates, but I don't know how to rewrite it so that it will sum the Cost3 field in the child table

before updating it on the parent table:
{

$str = "select ParentID from ChildCost where".$where;

$rs = db_query($str,$conn);

while ($data = db_fetch_array($rs))

{

$str2 = "update `ParentCost` set `Cost3`='".$values["Cost3"]."' where `ID`=".$data["ParentID"];
db_exec($str2,$conn);

}

}
Any help is much appreciated.

Thanks!

A
alang 1/23/2008
M
mrpeeble author 1/24/2008

This may be relevant http://www.asprunner.com/forums/index.php?...ost&p=25142


AlanG

I get what you're saying, but what i'm needing is the syntax to this query that you have aluded to

In addition, I'm also only summing the field based on a criteria.
Thanks