0

我有两张桌子,一张供用户使用,用于保存用户信息,另一张供朋友使用

users_table   :  id , username , avatar
friends_table :  id , u1_id , u2_id 

现在我想在他的个人资料中显示每个用户的朋友

我想用一个查询来做

所以在朋友表中,我的用户可能在 u1_id 或 u2_id 中,这取决于谁请求了友谊

因为我想将每个朋友加入 users_table 并获取他的用户名和头像,我不能简单地做

select * from friends_table where u1_id = $profile_id || u2_id = $profile_id

所以我必须运行两个查询

select f.u1_id , u.username , u.avatar from friends_table f join users_table u on f.u1_id = u.id
where f.u2_id = $profile_id 

select f.u2_id , u.username , u.avatar from friends_table f join users_table u on f.u2_id = u.id
where f.u1_id = $profile_id 

有没有办法用一个查询来做到这一点?

或类似的东西

select f.u1_id ,  f.u2_id , u.username , u.avatar from friends_table where u1_id = $profile_id || u2_id = $profile_id

if( u1_id = $profile_id )
join users_table u on f.u2_id = u.id

if( u2_id = $profile_id )
join users_table u on f.u1_id = u.id

我的问题是在加入部分,我想在朋友 ID 上加入 Friends_table 和 usres_table,而不是个人资料 ID 的当前所有者

4

1 回答 1

0
select u.id,
    u.username,
    u.avatar
from friends_table f
join users_table u on f.u1_id = u.id || f.u2_id = u.id
where u.ID <> $profile_id
    and (f.u1_id = $profile_id || f.u2_id = $profile_id)
于 2012-05-16T17:28:33.230 回答