Ho avuto questa query per iniziare con:Come rendere JOINS più veloce?
SELECT DISTINCT spentits.*
FROM `spentits`
WHERE (spentits.user_id IN
(SELECT following_id
FROM `follows`
WHERE `follows`.`follower_id` = '44'
AND `follows`.`accepted` = 1)
OR spentits.user_id = '44')
ORDER BY id DESC
LIMIT 15 OFFSET 0
Questa query richiede 10ms
da eseguire.
Ma una volta aggiungo un semplice unirsi:
SELECT DISTINCT spentits.*
FROM `spentits`
LEFT JOIN wishlist_items ON wishlist_items.user_id = 44 AND wishlist_items.spentit_id = spentits.id
WHERE (spentits.user_id IN
(SELECT following_id
FROM `follows`
WHERE `follows`.`follower_id` = '44'
AND `follows`.`accepted` = 1)
OR spentits.user_id = '44')
ORDER BY id DESC
LIMIT 15 OFFSET 0
Questa volta l'esecuzione aumentato di 11x
. Ora ci vuole circa 120ms
da eseguire. La cosa interessante è che se rimuovo la clausola oORDER BY id DESC
, il tempo torna a 10ms
.
Sono nuovo ai database quindi non lo capisco. Perché rimuovere una di queste clausole lo accelera 11x
? E come posso mantenerlo così com'è ma renderlo più veloce?
Ho indici su spentits.user_id
, follows.follower_id
, follows.accepted
e su primary ids
di ogni tabella.
SPIEGARE:
1 PRIMARY spentits index index_spentits_on_user_id PRIMARY 4 NULL 15 Using where; Using temporary
1 PRIMARY wishlist_items ref index_wishlist_items_on_user_id,index_wishlist_items_on_spentit_id index_wishlist_items_on_spentit_id 5 spentit.spentits.id 1 Using where; Distinct
2 SUBQUERY follows index_merge index_follows_on_follower_id,index_follows_on_following_id,index_follows_on_accepted
index_follows_on_follower_id,index_follows_on_accepted 5,2 NULL 566 Using intersect(index_follows_on_follower_id,index_follows_on_accepted); Using where
Cosa mostra EXPLAIN PLAN? –
@DavidJashi aggiornato con EXPLAIN – 0xSina