J'ai une table appelée ratings avec les champs suivants:
+-----------+------------+------+-----+---------+----------------+
| Champ | Type | Null | Clé | Défaut | Extra |
+-----------+------------+------+-----+---------+----------------+
| rating_id | bigint(20) | NON | PRI | NULL | auto_increment |
| user_id | int(11) | NON | MUL | NULL | |
| movie_id | int(11) | NON | | NULL | |
| rating | float | NON | | NULL | |
+-----------+------------+------+-----+---------+----------------+
Index sur cette table:
+---------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table | Non_unique | Nom_clé | Seq_in_index | Nom_colonne | Collation | Cardinalité | Sub_part | Emballé | Null | Type_index | Comment | Commentaire_index |
+---------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| ratings | 0 | PRIMARY | 1 | rating_id | A | 100076 | NULL | NULL | | BTREE | | |
| ratings | 0 | user_id | 1 | user_id | A | 564 | NULL | NULL | | BTREE | | |
| ratings | 0 | user_id | 2 | movie_id | A | 100092 | NULL | NULL | | BTREE | | |
+---------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
J'ai une autre table appelée movie_average_ratings
qui a les champs suivants:
+----------------+---------+------+-----+---------+-------+
| Champ | Type | Null | Clé | Défaut | Extra |
+----------------+---------+------+-----+---------+-------+
| movie_id | int(11) | NON | PRI | NULL | |
| average_rating | float | NON | | NULL | |
+----------------+---------+------+-----+---------+-------+
Comme il est évident à ce stade, je veux calculer la note moyenne des films à partir de la table ratings et mettre à jour la table movie_average_ratings
. J'ai essayé la requête SQL suivante.
UPDATE movie_average_ratings
SET average_rating = (SELECT AVG(rating)
FROM ratings
WHERE ratings.movie_id = movie_average_ratings.movie_id);
Actuellement, il y a environ 10 000 enregistrements de films et 100 000 enregistrements de notes et j'obtiens une erreur Lock wait timeout exceeded; try restarting transaction
. Le nombre d'enregistrements peut augmenter considérablement donc je ne pense pas qu'augmenter le temps d'attente soit une bonne solution.
Alors, comment puis-je écrire une requête 'évolutive' pour y parvenir? Est-ce que parcourir les enregistrements de la table movie_average_ratings
et calculer les moyennes individuellement est la solution la plus efficace?