1

我试图弄清楚如何在单个查询中完成以下任务。基本上,给定一个用户的 ID,我想返回他是朋友的所有用户的用户配置文件。如果有任何不清楚的地方,我很乐意提供更详细的信息。谢谢!

表“用户”:

 user_id  |  col1  |  col2   |  etc
-----------------------------------------
 a        |  ***   | ***     |  ***
-----------------------------------------
 b        |  ***   | ***     |  ***

表'users_friends'

 user_id  |  friend_user_id  |  status
-----------------------------------------
 a        |  b               |  1
-----------------------------------------
 b        |  a               |  1

给定a的值,在表users_friends中查找行

user_id = a
status = 1

使用该查询的结果行,在表users_friends中查找行

user_id = b          (column `user_friend_id` from resulting rows) 
user_friend_id = a   (column `user_id` from resulting rows) 
status = 1

如果返回任何行,请从表“用户”中选择行,其中

user_id = b          (column `user_id` from resulting row)

这是我想出的一个非常粗糙的方法。我认为它可以满足我的要求,但我确信有更好的方法来解决它。

SELECT * FROM users WHERE user_id IN 
    (SELECT user_id FROM users_friends WHERE friend_user_id IN
              (SELECT user_id FROM users_friends WHERE user_id = 'someuserid' AND status = 1 ) AND status = 1 );
4

3 回答 3

1
select u.*
from
    users u
    inner join
    users_friends f on u.user_id = f.friend_user_id
where
    f.status = 1
    and f.friend_user_id = 'a'
于 2013-03-07T23:55:45.407 回答
0

假设朋友表中没有重复项:

SELECT u.user_id, u.col1, u.col2
JOIN users_friends AS f1 ON u.user_id=f1.user_id
JOIN users_friends AS f2 ON f1.user_id=f2.friend_id AND f1.friend_id=f2.user_id
WHERE f1.status=1 AND f2.status=1 AND f2.user_id='a'
于 2013-03-07T23:54:14.093 回答
0

SQL小提琴

SELECT u.user_id, u.col1
FROM users_friends AS f
JOIN users AS u
    ON f.friend_user_id = u.user_id
WHERE f.user_id = 'a'
AND f.status = 1
于 2013-03-08T00:03:53.543 回答