我希望得到不是我朋友的朋友的朋友。 我有这样一张桌子: 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)
但我不确定它是否如此缓慢,或者它是否会以另一种方式更快。</ p>
对此有何看法?
答案 0 :(得分: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
)
;
答案 1 :(得分: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
,因为它们将利用相关字段上的索引进行比较。另一方面,子查询将针对返回的每一行执行,即使它是非相关子查询(MySQL)。
答案 2 :(得分: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';
答案 3 :(得分: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情况下使用子查询。