SQL连接和子查询,子查询到SQL连接

时间:2013-02-27 14:02:16

标签: mysql sql performance join subquery

我写了这个SQL查询,以获取不在邀请表中的用户的朋友,并且它可以工作,但我读到子查询是性能消费者,我对JOINS不是很好,任何帮助修改此查询到只是加入将非常感激。

这是SQL查询

SELECT friend.id,
       friend.first_name
FROM   friends AS friend
       INNER JOIN friends_users AS friendsUser
         ON ( friend.id = friendsUser.friend_id
              AND friend.id NOT IN (SELECT friend_id
                                    FROM   friends_invitations
                                    WHERE  friends_invitations.user_id = 1) )
ORDER  BY friendsUser.id ASC 

以下是表格结构

friends
id   first_name

friends_users
id  friend_id  user_id

friends_invitations
id  friend_id user_id

任何帮助都将非常感激

2 个答案:

答案 0 :(得分:1)

子查询不一定是表演者,您的查询是否存在性能问题?无论如何,大多数时候,查询的最快方式是使用NOT EXISTS

SELECT  friend.id, 
        friend.first_name 
FROM friends AS friend 
INNER JOIN friends_users AS friendsUser 
    ON friend.id = friendsUser.friend_id  
WHERE NOT EXISTS (SELECT 1 FROM friends_invitations 
                  WHERE friends_invitations.user_id = 1
                  AND friend_id = friend.id)
ORDER BY friendsUser.id ASC

Here is a link解释了NOT INLEFT JOINNOT EXISTS(对于SQL Server)之间的差异。因此,请测试这些不同的选项,并为您的表选择合适的选项。

答案 1 :(得分:0)

您可以使用LEFT JOIN

SELECT  friend.id,
        friend.first_name
FROM    friends AS friend
        INNER JOIN friends_users AS friendsUser
            ON friend.id = friendsUser.friend_id 
        LEFT JOIN   friends_invitations
            ON friend.id = friends_invitations.friend_id AND
                friends_invitations.user_id = 1
WHERE   friends_invitations.friend_id IS NULL
ORDER   BY friendsUser.id ASC