[英]Getting information from “users” table about users who I'm friends with. relational/join SQL table?
[英]combining two queries : selecting friends from friend table and join tham with users table
我有两个表,一个供用户使用,可保留用户信息,另一个供朋友使用
users_table : id , username , avatar
friends_table : id , u1_id , u2_id
现在我想在他的个人资料中显示每个用户朋友
我想用一个查询做到这一点
因此在friends表中,根据谁请求了友谊,我的用户可能在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而不是个人资料ID的当前拥有者的usres_table中加入friends_table
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.