我有2个表word_lists
和memo_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记录?
答案 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;
这将使您的表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
)