使用group by sum更新表

时间:2011-03-04 17:12:08

标签: mysql

我有两张桌子。一个是包含数量信息的详细信息表,具有以下结构

> mysql> DESCRIBE summary_finished;
+---------------+---------------+------+-----+---------+
| Field         | Type          | Null | Key | Default |
+---------------+---------------+------+-----+---------+
| db_id         | int(11)       | NO   | PRI | NULL    |
| finished_id   | text          | NO   |     | NULL    |
| finished_name | text          | NO   |     | NULL    |
| qoh           | int(11)       | NO   |     | NULL    |
| value         | decimal(10,2) | NO   |     | NULL    |                
+---------------+---------------+------+-----+---------+


    mysql> DESCRIBE detail_finished;
    +-------------+---------------+------+-----+---------+
    | Field       | Type          | Null | Key | Default |
    +-------------+---------------+------+-----+---------+
    | db_id       | int(11)       | NO   | PRI | NULL    |
    | finished_id | text          | NO   |     | NULL    |
    | quantity    | int(11)       | NO   |     | NULL    |
    | value       | decimal(10,2) | NO   |     | NULL    |
    +-------------+---------------+------+-----+---------+

在detail_finished中,有许多项具有相同的finished_id。我想要完成的是组合具有相同finished_id的项目并将该总和更新到summary_finished.qoh字段。这就是我到目前为止所做的:

function set_qty($total, $finished_id){
    global $connection;
    $query="UPDATE summary_finished 
    SET qoh={$total} 
    WHERE finished_id='$finished_id'";
    $quantity=mysql_query($query, $connection);
    confirm_query($quantity);
    }


$query="SELECT finished_id, SUM(quantity) FROM detail_finished GROUP BY finished_id";
$result=mysql_query($query, $connection) or die(mysql_error());

while($row = mysql_fetch_array($result)){
  set_qty($row['SUM(quantity)'], $row['finished_id']);
   }

我知道总和正在计算正确,因为我可以直接回应它们,但是我无法让我的表更新。请原谅我的代码,我完全不熟悉mysql。提前感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

我不知道为什么你使用文本类型来存储id。顺便说一句

 update summary_finished as sf
 inner join (
 select finished_id, 
        sum(quantity) as total
 from detail_finished 
 group by finished_id )as t
 set sf.qoh = t.total
 where sf.finished_id = t.finished_id