0

所以前几天,我问了这个关于如何组合三个复杂查询的问题,并找到了一种方法。现在我正在尝试使用这些查询来更新用户表中的字段,但找不到使其工作的方法。这是查询:

update users set field_sum =(
    select sum(field_sum) from (
        select sum(field_one) as field_sum
          from t_a join t_b on (t_a.bid = t_b.id) where t_b.user_id=users.id 
        union all
        select sum(field_two) as field_sum
          from t_c join t_d on (t_c.did = t_d.id) where t_d.user_id=users.id 
        union all
        select sum(field_three) as field_sum
          from t_e where t_e.user_id=users.id
    ) as field_sumT
)

当我尝试运行它时,我收到以下错误:ERROR 1054 (42S22): Unknown column 'users.id' in 'where clause'. 当我尝试.user_id=users.id从每个 where 子句中删除该位时,它将运行但最终得到 field_sum 的总和,而不仅仅是该用户的 field_sum。有没有办法做到这一点?

4

1 回答 1

1

采用:

    UPDATE USERS u
LEFT JOIN (SELECT t_b.user_id,
                  SUM(field_one) as field_sum 
             FROM t_a 
             JOIN t_b on t_a.bid = t_b.id
         GROUP BY t_b.user_id) a ON a.user_id = u.id
LEFT JOIN (SELECT t_d.user_id,
                  SUM(field_two) as field_sum 
             FROM t_c 
             JOIN t_d on t_c.did = t_d.id
         GROUP BY t_d.user_id) b ON b.user_id = u.id
LEFT JOIN (SELECT t_e.user_id,
                  SUM(field_three) as field_sum 
             from t_e 
         GROUP BY t_e.user_id) c ON c.user_id = u.id
      SET field_num = COALESCE(a.field_sum, 0) + COALESCE(b.field_sum, 0) + COALESCE(c.field_sum, 0)

警告

这会将支持行中没有记录的任何用户设置为 field_sum 值为零。您是否只想更新至少在其中一个表中有记录的那些?

于 2010-10-06T03:57:42.330 回答