0

我正在尝试寻找共同的朋友。

我有一个结构如下的表:

 `friends` (   
    `inviter`  int(11) NOT NULL,   
    `accepter`  int(11) NOT NULL,   
    `time` datetime NOT NULL,)
ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_turkish_ci;

我的load_my_friends(##MY ID##);查询是这样的:

SELECT  p.id , p.name,p.lastname,p.thumb
FROM  friends AS f
RIGHT JOIN  profiles AS p ON ( f.accepter = p.id OR f.inviter = p.id ) 
WHERE  f.inviter = ##MY ID##
OR  f.accepter = ##MY ID##
LIMIT 0 , 5000

你能告诉我如何获取共同朋友的数据吗?

注意:我没有使用任何社交网络脚本,如 JCOW、Social Engine 等。


编辑@2

在数据库中我有 user1,user2,user3,user4,user5..userX

  • user1的朋友是:2,3,6,7,8
  • user2的朋友是:1,3,4,5,7,8

我想要一个可以获取这些结果的查询:

     | id  | name |lastname| thumb
    1|  3  |raheel|shan    | /img01.jpg
    2|  7  | arqu |x       | /img02.jpg
    3|  8  |abcdef|hijklmno| /img06.jpg
4

4 回答 4

2

一个可能很容易理解的查询如下:

SELECT p.* 
FROM 
    (
       -- all friends of User A
       SELECT accepter AS friend_id FROM friends WHERE inviter IN (##User_A_ID##)
       UNION
       SELECT inviter AS friend_id FROM friends WHERE accepter IN (##User_A_ID##)
    ) AS t1
    -- intersect with
    JOIN
    (
       -- all friends of User B
       SELECT accepter AS friend_id FROM friends WHERE inviter IN (##User_B_ID##)
       UNION
       SELECT inviter AS friend_id FROM friends WHERE accepter IN (##User_B_ID##)
    ) AS t2
    ON t1.friend_id = t2.friend_id

    JOIN profiles p on p.id=t1.friend_id
于 2013-01-26T00:01:14.410 回答
0

也许有人可以想出一个更简单的方法来做到这一点,但这是我的尝试:

SELECT id,name,lastname FROM profiles, 
  (SELECT *
   FROM friends 
   WHERE  
       (inviter = 1 OR accepter = 1) 
       AND (accepter IN ( 
             SELECT inviter 
             FROM   friends 
             WHERE  accepter = 2 AND inviter != 1)
          OR accepter IN ( 
             SELECT accepter 
             FROM   friends 
             WHERE  inviter = 2 AND accepter != 1)
          OR inviter IN ( 
             SELECT inviter 
             FROM   friends 
             WHERE  accepter = 2 AND inviter != 1)
          OR inviter IN (
             SELECT accepter
             FROM   friends 
             WHERE  inviter = 2 AND accepter != 1)))
    f
    WHERE id != 1 AND (inviter = id OR accepter = id);

其中 user1 的 id = 1,而 user2 的 id = 2

看看 - http://sqlfiddle.com/#!2/15951/8

于 2013-01-25T20:15:43.563 回答
0

如果您只是想要一个在两个用户(User_A 和 User_B)之间共享的朋友列表,那么这可能就足够了:

SELECT accepter 
FROM   friends 
WHERE  inviter = ##User_A_ID## 
       AND accepter IN ( 
          SELECT accepter 
          FROM   friends 
          WHERE  inviter = ##User_B_ID## )

加入您的配置文件表以获取其他相关数据。

于 2013-01-25T21:04:01.997 回答
0
SELECT * 
FROM profiles p
WHERE p.id IN (
    SELECT f_id 
    FROM (
        SELECT accepter as f_id FROM friends where inviter IN (1,2)
        UNION
        SELECT inviter as f_id FROM friends where accepter IN (1,2)
    ) friends 
    GROUP BY f_id
    HAVING count(*) > 1
)

假设友谊是唯一的行....

于 2013-01-25T22:11:27.957 回答