计算MySQL中每个用户的平均消息质量

时间:2012-07-25 09:56:34

标签: mysql

考虑以下表格:

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可以是01。我需要计算每个用户的平均邮件质量并相应地更新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

2 个答案:

答案 0 :(得分: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

如果您从一个空的用户表开始,您可以像这样运行一个查询来全部更新:

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)

答案 1 :(得分: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;