编写一个查询,给出用户DDD和FFF的共同朋友名称。另外,请注意,如果A是B的朋友,那么B也是朋友A.

时间:2017-07-06 09:00:49

标签: sql oracle

创建包含朋友和用户列表的2个表。

这是我的疑问:

class(df[1,1)=="labelled", "numeric"

朋友:userid,friendid

SELECT
  U.username "Mutual Friend"
FROM users U
LEFT OUTER JOIN friends F
  ON U.userid = F.friendid
WHERE f.userid = 6
AND f.friendid IN (SELECT
  friendid
FROM friends
WHERE userid = 4);

用户:userid,用户名

1, 2
1, 3
1, 4
2, 4
2, 5
2, 7
3, 4
3, 6
4, 7
4, 8
4, 9
5, 6
5, 9
6, 7
7, 8
8, 9

期望的结果:

1, AAA
2, BBB
3, CCC
4, DDD
5, EEE
6, FFF
7, GGG
8, HHH
9, III

2 个答案:

答案 0 :(得分:1)

  

EDITED

SELECT users.username FROM (
    SELECT
     CASE WHEN userid = 4 THEN friendid else userid END AS "MUTUAL"
    FROM friends
    WHERE (userid = 4 OR friendid = 4) AND
          ( 
          friendid in (SELECT friendid from friends where userid = 6) OR
          friendid in (SELECT userid from friends where friendid = 6) OR
          userid in (SELECT friendid from friends where userid = 6) OR
          userid in (SELECT userid from friends where friendid = 6) 
          )
    ), users WHERE MUTUAL = users.userid

答案 1 :(得分:1)

您可以使用having

SELECT     u.username "Mutual Friend" 
FROM       users u
INNER JOIN friends f 
        ON u.userid IN (f.userid, f.friendid)
INNER JOIN users v
        ON v.userid IN (f.userid, f.friendid)
       AND v.userid <> u.userid
       AND v.username IN ('DDD', 'FFF')
GROUP BY   u.username
HAVING     count(distinct v.userid) = 2