简体   繁体   English

SQL联接和子查询,SQL联接的子查询

[英]SQL joins and Subqueries , Subquery to SQL joins

I wrote this SQL query to get friends of user who is not in the invitation table , and it works will , however i read that subqueries are performance eaters and I am not very good with JOINS, any help for modifying this query to be just in joins will be really appreciated. 我编写此SQL查询是为了获得不在邀请表中的用户的朋友,并且该函数可以正常工作,但是我读到子查询是性能消耗者,并且我对JOINS不太满意,将此查询修改为仅在其中的任何帮助加入将不胜感激。

Here is the SQL Query 这是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 

Here is the tables structure 这是表格结构

friends
id   first_name

friends_users
id  friend_id  user_id

friends_invitations
id  friend_id user_id

Any help will be really appreciated 任何帮助将不胜感激

A subquery is not necessarily a performance eater, is your query presenting performance issues?. 子查询不一定是性能消耗者,您的查询是否存在性能问题? Anyway, most times the fastest way to do your query would be using a NOT EXISTS : 无论如何,大多数时候执行查询的最快方法是使用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 explaining the differences between NOT IN , LEFT JOIN and NOT EXISTS (for SQL Server). 这是一个链接,解释NOT INLEFT JOINNOT EXISTS (对于SQL Server)之间的区别。 So, test this different options and choose the right one for your tables. 因此,测试此不同选项并为您的表选择正确的选项。

you can use LEFT JOIN for this, 您可以为此使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM