Tôi đã truy vấn này để bắt đầu với:Làm thế nào để làm cho JOINS nhanh hơn?
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
truy vấn này có 10ms
để thực thi.
Nhưng một khi tôi thêm một đơn giản tham gia:
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
này thực hiện thời gian tăng 11x
. Bây giờ phải mất khoảng 120ms
để thực thi. Điều thú vị là nếu tôi xóa một trong các điều khoản LEFT JOIN
hoặc số ORDER BY id DESC
, hãy quay lại 10ms
.
Tôi mới sử dụng cơ sở dữ liệu nên tôi không hiểu điều này. Tại sao việc xóa một trong hai mệnh đề này lại tăng tốc độ lên 11x
? Và làm thế nào tôi có thể giữ nó như là nhưng làm cho nó nhanh hơn?
Tôi có chỉ mục trên spentits.user_id
, follows.follower_id
, follows.accepted
và trên primary ids
của mỗi bảng.
GIẢI THÍCH:
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
EXPLAIN PLAN hiển thị những gì? –
@DavidJashi được cập nhật với GIẢI THÍCH – 0xSina