我已经尝试过很多关于内连接,外连接的例子,甚至尝试通过猜测来实现我自己(这通常更有效)但在这里没有运气。
表1: follower_user_id,followed_user_id
(注意它的跟随者 R _并跟随 D _)
表2: user_id,用户名
所以我需要表2中的两行,其中一个user_id匹配follower_user_id,另一行user_id匹配follow_user_id
查询中的查询有效,但我知道这不是可行的方法......
SELECT f.*, u.*
FROM tbl_follows f, tbl_users u
WHERE follower_user_id = u.user_id
这是基本查询
while($row = $r->fetch_assoc()){
//here i make another query to get the username of the followed_user_id
}
当然这可以在一个查询中完成吗?
提前致谢
---更新1:样本数据---
tbl_users
user_id | username
--------------------------------------
1 | abc123
2 | xyz789
3 | nosey123
tbl_follows
follower_user_id | followed_user_id
-------------------------------------------
3 | 2 //nosey123 is following xyz789
3 | 1 //nosey123 is following abc123
1 | 2 //abc123 is following xyz789
While Results
:
echo "$row[username] is following $row['???????']<br />"
我正在寻找:
nosey123 is following xyz789
nosey123 is following abc123
abc123 is following xyz789
答案 0 :(得分:0)
你尝试过这样的事吗?
SELECT f.*, u.*
FROM tbl_follow f
JOIN tbl_users u ON u.user_id = f.follower_user_id OR u.user_id = f.followed_user_id;
这应该为每个userID返回两行,因为跟随者用户将有一个匹配,后续用户将匹配一个。
答案 1 :(得分:0)
SELECT DISTINCT(A.user_id), A.username, B.*
FROM tbl_follow A
JOIN tbl_users B
ON B.user_id = A.follower_user_id
OR B.user_id = A.followed_user_id;