使用GROUP BY更新所有相关记录

时间:2012-12-29 18:21:42

标签: mysql sql ruby-on-rails join

我有2个表word_listsmemo_words,word_list有很多memo_words(1 - n)。

TABLE: word_lists
+----+----------+----------------+
| id | name     | average_rating |
+----+----------+----------------+
| 1  | example1 |       ?        |
| 2  | example2 |       ?        |
| 3  | example3 |       ?        |
+----+----------+----------------+
ID is primary

TABLE: memo_words
+----+----------+-------+-------------------+
| id | name     | rating| word_list_id      |
+----+----------+-------+-------------------+
| 1  | random1  |  153  | 1                 |
| 2  | random2  |  158  | 1                 |
| 3  | random3  |  167  | 1                 |
+----+----------+-------+-------------------+
ID is primary

我想为每个word_lists记录计算word_lists.average_rating。平均评分对于每个memo_words记录,它是memo_words.rating的平均值。对于计算平均值,我可以使用这样的东西:

  SELECT id, AVG(rating) from memo_words group_by word_list_id;

但是如何更新word_lists记录?

3 个答案:

答案 0 :(得分:1)

Update word_lists w inner join 
(select AVG(rating) rating,word_list_id from memo_words
 group by word_list_id) m on w.id=m.word_list_id
set w.average_rating=m.rating

试试这个

答案 1 :(得分:1)

这是带有UPDATE的MySQL JOIN语法:

UPDATE word_lists w
INNER JOIN
(
   SELECT 
     word_list_id,
     AVG(rating) averageRating
   FROM memo_words 
   GROUP BY word_list_id
) m ON w.Id = m.word_list_id
SET w.average_rating = m.averageRating;

SQL Fiddle Demo

这将使您的表memo_words看起来像:

| ID |     NAME | AVERAGE_RATING |
----------------------------------
|  1 | example1 |            159 |
|  2 | example2 |         (null) |
|  3 | example3 |         (null) |

答案 2 :(得分:1)

最简单的方法是:

Update word_list
    set average_rating = (select AVG(mw.rating)
                          from memo_words mw
                          where mw.word_list_id = word_list.id
                         )