Mysql双连接更新

时间:2012-08-31 11:33:34

标签: mysql sql sql-update

我有三个表:对象,关系,点

关系表将多个点连接到对象。想象一下这样的表结构:

**OBJECTS**
  |object_id|object_name|object_points|
**RELATIONS**
  |relation_id|relation_object_id|relation_point_id|
**POINTS**
  |point_id|point_value(INT)|

如何在UPDATE中进行“双联接”以从相关object_points的总和中续订对象表字段point_values

2 个答案:

答案 0 :(得分:2)

这样的东西?

UPDATE
        Objects AS o
    JOIN
        ( SELECT 
              r.relation_object_id
            , SUM(point_value) AS total_points
          FROM
                  Relations AS r
              JOIN
                  Points AS p
                ON p.point_id = relation_point_id 
          GROUP BY
              r.relation_object_id
        ) AS grp
      ON grp.relation_object_id = o.object_id
SET
    o.object_points = grp.total_points ;

答案 1 :(得分:0)

这应该有效

Update OBJECTS set object_points=(select sum(POINTS.point_value) 
  from RELATIONS,POINTS where 
  RELATIONS.relation_object_id=OBJECTS.object_id 
  and RELATIONS.relation_point_id=POINTS.point_id group by relation_object_id)

这是工作演示:http://sqlfiddle.com/#!2/d2a9f/1/0