Comment faire une mise à jour efficace comme mon SELECT dans MariaDB
Arrière-plan
J'ai créé un petit tableau de 10 lignes à partir d'un précédent SELECT déjà exécuté (SavedAnimals).
J'ai une table massive (animaux) que je voudrais METTRE À JOUR en utilisant les lignes avec le même identifiant que chaque ligne de ma nouvelle table.
Ce que j'ai essayé jusqu'à présent
Je peux rapidement SÉLECTIONNER les lignes souhaitées dans la grande table comme ceci :
mysql> EXPLAIN SELECT * FROM animals WHERE ignored=0 and id IN (SELECT animal_id FROM SavedAnimals);
+------+--------------+-------------------------------+--------+---------------+---------+---------+----------------------------------------------------------+------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+------+--------------+-------------------------------+--------+---------------+---------+---------+----------------------------------------------------------+------+-------------+
| 1 | PRIMARY | <subquery2> | ALL | distinct_key | NULL | NULL | NULL | 10 | |
| 1 | PRIMARY | animals | eq_ref | PRIMARY | PRIMARY | 8 | db_staging.SavedAnimals.animal_id | 1 | Using where |
| 2 | MATERIALIZED | SavedAnimals | ALL | NULL | NULL | NULL | NULL | 10 | |
+------+--------------+-------------------------------+--------+---------------+---------+---------+----------------------------------------------------------+------+-------------+
Mais la "même" commande sur le UPDATE n'est pas rapide :
mysql> EXPLAIN UPDATE animals SET ignored=1, ignored_when=CURRENT_TIMESTAMP WHERE ignored=0 and id IN (SELECT animal_id FROM SavedAnimals);
+------+--------------------+-------------------------------+-------+---------------+---------+---------+------+----------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+------+--------------------+-------------------------------+-------+---------------+---------+---------+------+----------+-------------+
| 1 | PRIMARY | animals | index | NULL | PRIMARY | 8 | NULL | 34269464 | Using where |
| 2 | DEPENDENT SUBQUERY | SavedAnimals | ALL | NULL | NULL | NULL | NULL | 10 | Using where |
+------+--------------------+-------------------------------+-------+---------------+---------+---------+------+----------+-------------+
2 rows in set (0.00 sec)
La commande UPDATE ne se termine jamais si je l'exécute.
QUESTION
Comment puis-je faire fonctionner mariaDB avec le select_type matérialisé sur le UPDATE comme il le fait sur le SELECT ?
OU ALORS
Y a-t-il une manière totalement distincte d'aborder cela qui serait rapide ?
Remarques
Version : 10.3.23-MariaDB-journal
Solution du problème
Utilisez JOIN
plutôt que WHERE...IN
. MySQL a tendance à mieux les optimiser.
UPDATE animals AS a
JOIN SavedAnimals AS sa ON a.id = sa.animal_id
SET a.ignored=1, a.ignored_when=CURRENT_TIMESTAMP
WHERE a.ignored = 0
Commentaires
Enregistrer un commentaire