为什么一个查询比另一个更快?

时间:2013-06-04 15:38:07

标签: mysql sql

这是一个查询:

SELECT DISTINCT
    spentits.*,
    username,
    (SELECT count(*) from likes where likes.spentit_id = spentits.id) as like_count,
    (SELECT count(*) from comments where comments.spentit_id = spentits.id) as comment_count,
    (SELECT count(*) from wishlist_items where wishlist_items.spentit_id = spentits.id) as wishlist_count,
    (case when likes.id is null then 0 else 1 end) as is_liked_by_me,
    (case when wishlist_items.id is null then 0 else 1 end) as is_wishlisted_by_me
FROM spentits
LEFT JOIN users ON users.id = spentits.user_id
LEFT JOIN likes ON likes.user_id = 9 AND likes.spentit_id = spentits.id
LEFT JOIN wishlist_items ON wishlist_items.user_id = 9 AND wishlist_items.spentit_id = spentits.id
WHERE spentits.user_id IN
    (SELECT follows.following_id
     FROM follows
     WHERE follows.follower_id = 9)
ORDER BY id DESC 
LIMIT 15;

这需要执行平均43ms次。现在另一个查询(下面),没有where子句,更不用说第二个SELECT子查询执行速度慢5倍240ms)!

SELECT DISTINCT
    spentits.*,
    username,
    (SELECT count(*) from likes where likes.spentit_id = spentits.id) as like_count,
    (SELECT count(*) from comments where comments.spentit_id = spentits.id) as comment_count,
    (SELECT count(*) from wishlist_items where wishlist_items.spentit_id = spentits.id) as wishlist_count,
    (case when likes.id is null then 0 else 1 end) as is_liked_by_me,
    (case when wishlist_items.id is null then 0 else 1 end) as is_wishlisted_by_me
FROM spentits
LEFT JOIN users ON users.id = spentits.user_id
LEFT JOIN likes ON likes.user_id = 9 AND likes.spentit_id = spentits.id
LEFT JOIN wishlist_items ON wishlist_items.user_id = 9 AND wishlist_items.spentit_id = spentits.id
ORDER BY id DESC 
LIMIT 15;

为什么呢?第二个查询不应该快得多,因为没有条件,没有第二个查询。所有数据库需要做的是选择最后15条记录,与执行子查询后检查每条记录需要扫描的第一条记录进行比较,并检查其中是否包含ID。我真的很困惑一个应该执行速度快得多的查询实际上要慢5倍。

1 个答案:

答案 0 :(得分:1)

存在与统计信息和元数据相关的执行路径,为两者执行explain plan并查看执行路径。

此外,如果您没有按照该ID过滤投影行,则按ID过滤可能会对没有匹配行的表执行跳过。