0

我编写了这个 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

任何帮助将不胜感激

4

2 回答 2

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

这是一个链接NOT IN,解释了,LEFT JOINNOT EXISTS(对于 SQL Server)之间的区别。因此,测试这些不同的选项并为您的桌子选择正确的选项。

于 2013-02-27T14:12:00.600 回答
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
于 2013-02-27T14:04:48.757 回答