1

我想得到不是我朋友的朋友的朋友。我有一个这样的表: userFriends(idUser, idUserFriend)

我在想这样的事情:

select distinct idUserFriend from userFriends where idUser in
(select idUserFriend from userFriends where idUser = 1)
and idUserFriend not in (select idUserFriend from userFriends where idUser = 1)

但我不确定它是否如此缓慢,或者它是否可以以另一种方式更快。

对此有何看法?

4

4 回答 4

3
SELECT DISTINCT
    two.idUserFriend
FROM userFriends one
JOIN userFriends two ON one.idUserFriend = two.idUser
WHERE NOT EXISTS (
        SELECT * 
        FROM userFriends nx
        WHERE nx.idUser = one.idUser
        AND nx.idUserFriend = two.idUserFriend
        )
AND one.idUser = 1
        ;

同样可以通过“NOT IN”构造来完成:

SELECT DISTINCT
    two.idUserFriend
FROM userFriends one
JOIN userFriends two ON one.idUserFriend = two.idUser
WHERE two.idUserFriend NOT IN (
        SELECT  nx.idUserFriend
        FROM userFriends nx
        WHERE nx.idUser = one.idUser
        )
AND one.idUser = 1
        ;

还有“EXCEPT”版本:

SELECT DISTINCT
    two.idUserFriend
FROM userFriends one
JOIN userFriends two ON one.idUserFriend = two.idUser
WHERE one.idUser = 1
EXCEPT (
        SELECT  nx.idUserFriend
        FROM userFriends nx
        WHERE nx.idUser = 1
        )
        ;
于 2012-06-21T11:27:29.020 回答
1

使用连接进行比较:

SELECT
    b.idUserFriend
FROM 
    userFriends a
INNER JOIN
    userFriends b ON a.idUserFriend = b.idUser
LEFT JOIN
    userFriends c ON a.idUser = c.idUser AND b.idUserFriend = c.idUserFriend
WHERE
    a.idUser = 1
    AND c.idUser IS NULL
GROUP BY
    b.idUserFriend #eliminate duplicates

通常,最好JOIN在子查询上使用 s,因为它们将利用相关字段上的索引进行比较。另一方面,子查询将针对返回的每一行执行,即使它是不相关的子查询 (MySQL)。

有关JOIN 与子查询的更多信息

于 2012-06-21T11:11:45.227 回答
1
select myFriend.idUserFriend from userFriend me inner join userFriends myFriend 
on me.idUserFriend = myFriend.idUser and myFriend.idUserFriend != me.idUserFriend 
where me.idUser='MyUserId';
于 2012-06-21T11:12:02.840 回答
1

试试这个 -

SELECT UF2.idUser, UF2.idUserFriend 
FROM USERFIRENDS UF2 INNER JOIN 
(
    SELECT idUser, idUserFriend
    FROM USERFRIENDS UF1
    WHERE UF1.idUser =1 -- this query gives my friend
) MYFRIENDS ON 
      UF2.idUser=MYFRIENDS.idUserFriend -- get my freinds friends
      AND UF2.idUserFriend NOT IN 
           (
              SELECT idUserFriend
              FROM USERFRIENDS UF1
              WHERE UF1.idUser =1           
           )

此查询的优点是第一个子查询是连接的一部分,不会对每条记录都执行。

不幸的是,您需要为 NOT IN case 使用子查询。

于 2012-06-21T11:26:00.923 回答