[英]Selecting 2 rows from same table for different criterias
我尝试了许多内部联接,外部联接的示例,甚至尝试用猜测来迷惑我自己(这常常会奏效),但是在这里没有运气。
表1:follower_user_id,followed_user_id
(请注意,它是跟随者R _和跟随者D _)
表2:user_id,用户名
因此,我需要表2中的两行,其中一个user_id匹配follower_user_id,另一行其中user_id匹配followed_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
你尝试过这样的事情吗?
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返回两行,因为对于追随者用户将有一个匹配项,而对于跟随用户将有一个匹配项。
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.