2

考虑下表:

users                    messages
-------------------      ----------------------
user_id avg_quality      msg_id user_id quality
-------------------      ----------------------
1                        1      1       1
2                        2      1       0
3                        3      1       0
                         4      1       1
                         5      1       1
                         6      2       0
                         7      2       0
                         8      3       1

messages.quality要么0要么1。我需要计算每个用户的平均消息质量并users.avg_quality相应地更新。因此,所需的输出将被修改为users如下表:

users
-------------------
user_id avg_quality  <-- DECIMAL (8,2)
-------------------
1       0.60         <-- (3x1 + 2x0) / 5
2       0.00         <-- (2x0) / 2
3       1.00         <-- (1x1) / 1

我已经开始这样的查询,我知道语法不正确但没有更好的主意。你?

UPDATE messages m, users u
SET avg_quality = (SELECT COUNT(m.msg_id) / SUM(m.quality))
WHERE m.user_id = u.user_id
4

2 回答 2

1

查看平均函数:

http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_avg

您的选择应该是这样的:

select user_id, AVG(quality) from messages group by user_id

如果你从一个空的 users 表开始,你可以运行一个像这样的查询来更新它:

insert into users (user_id, avg_quality)
select m.user_id, coalesce(AVG(m.quality),0) from messages m group by m.user_id

如果您需要持续的结果,Luc 的建议将为您工作:

update users u left join (
    select m.user_id, AVG(m.quality) as average from messages m group by m.user_id  
) as average_result_t on u.user_id = average_result_t.user_id
set u.average = coalesce(average_result_t.average,0)
于 2012-07-25T09:58:49.930 回答
1

这应该有效:

UPDATE users u
       INNER JOIN (SELECT a.user_id, AVG(quality) avg_quality 
                   FROM messages a
                        INNER JOIN users b
                            ON a.user_id = b.user_id
                   GROUP BY a.user_id
                  ) tmp
                  ON u.user_id = tmp.user_id
SET u.avg_quality = tmp.avg_quality;
于 2012-07-25T10:00:12.037 回答