1

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

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)如何删除子查询并改用 JOINS,b)使用 JOINS 代替子查询会带来性能优势吗?

(follows.following_id、follows.follower_id、pictures.user_id 都被索引)

谢谢

4

1 回答 1

4
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

要进一步了解有关联接的更多信息,请访问以下链接:

更新

实现相同结果的另一种方法是使用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
于 2013-06-01T17:43:49.287 回答