1

我有 2 个表word_listsmemo_wordsword_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.rating 中每个相关的 memo_words 记录的平均值。为了计算平均值,我可以简单地使用这样的东西:

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

但是我怎样才能更新 word_lists 记录呢?

4

3 回答 3

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

试试这个

于 2012-12-29T18:24:48.500 回答
1

这是 MySQL 的UPDATE语法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 小提琴演示

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

| ID |     NAME | AVERAGE_RATING |
----------------------------------
|  1 | example1 |            159 |
|  2 | example2 |         (null) |
|  3 | example3 |         (null) |
于 2012-12-29T18:31:00.870 回答
1

最简单的方法是:

Update word_list
    set average_rating = (select AVG(mw.rating)
                          from memo_words mw
                          where mw.word_list_id = word_list.id
                         )
于 2012-12-29T18:32:11.510 回答