我正在试图找到共同的朋友。
我有一个像这样的结构表:
`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,社交引擎等。
编辑@ 2
在数据库中我有user1,user2,user3,user4,user5..userX
我想要一个可以获取这些结果的查询:
| id | name |lastname| thumb
1| 3 |raheel|shan | /img01.jpg
2| 7 | arqu |x | /img02.jpg
3| 8 |abcdef|hijklmno| /img06.jpg
答案 0 :(得分: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
答案 1 :(得分: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
答案 2 :(得分: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## )
加入您的个人资料表以获取其他相关数据。
答案 3 :(得分: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
)
假设友谊是唯一的行......