用于获取好友列表的SQL查询

时间:2012-10-23 22:57:25

标签: php mysql

我需要SQL查询的帮助。

我有两张桌子。一个是用户,另一个是用户朋友

users table:
aid email                    firstname 
1   example@mail.com         example
2   example2@mail.com        example2
3   example3@mail.com        example3
4   example4@mail.com        example4

userfriends tables:
reqid     email                    friendemail               status 
1         example1@mail.com        example2@mail.com            1       (example1 is frnds with example2)
2         example2@mail.com        example4@mail.com            2       (example2 request pending)
3         example3@mail.com        example1@mail.com            1       (example1 is frnds with example3)
4         example4@mail.com        example1@mail.com            1       (example1 is frnds with example4)

因此,当状态为2时,添加请求处于待处理状态,而状态1处则是朋友。我想要的是我想要检索用户example1的完整好友列表。我想从users表中提取名称,以便从上一个查询中显示相应的输出,以显示为friendlist。

3 个答案:

答案 0 :(得分:1)

select distinct friendemail
from userfriends f
inner join users u on u.email = f.email
where f.status = 1
and u.firstname = 'example'

答案 1 :(得分:0)

您需要JOIN两个表:

SELECT users.firstname 
    FROM userfriends UF 
    JOIN users U ON (U.email=UF.friendemail)
WHERE UF.email='your user'

答案 2 :(得分:0)

我认为你们错过了搜索到的电子邮件可以在任何一栏中的事实:

select u.firstname
from userfriends f, users u where 
u.email='email@domain.com' and f.status=1 and
(u.email = f.email and f.friendsemail='email@domain.com')
or
(u.email = f.friendsemail and f.email='email@domain.com')