我有一个使用子查询的简单查询:

SELECT pictures.*
FROM pictures
WHERE pictures.user_id IN
    (SELECT follows.following_id
     FROM follows
     WHERE follows.follower_id = 9)
ORDER BY created_at DESC LIMIT 5;

我想知道,
a)如何删除子查询并改用联接;b)使用联接而不是子查询是否有性能优势?
(follows.following_id,following.follower_id,pictures.user_id都被索引)
谢谢

最佳答案

SELECT  DISTINCT pictures.*
FROM    pictures
        INNER JOIN follows
            ON pictures.user_ID = follows.following_id
WHERE   follows.follower_id = 9
ORDER   BY pictures.created_at DESC
LIMIT   5

若要进一步了解有关联接的更多信息,请访问以下链接:
Visual Representation of SQL Joins
更新
实现相同结果的另一种方法是使用EXISTS
SELECT  *
FROM    pictures
WHERE   EXISTS
        (
            SELECT  1
            FROM    follows
            WHERE   pictures.user_ID = follows.following_id AND
                    follows.follower_id = 9
        )
ORDER   BY pictures.created_at DESC
LIMIT   5

关于mysql - 使用JOINS代替子查询,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16875432/

10-11 11:46