0
SELECT
    FRIEND.friend_two AS possible_friend, USERS.username AS possible_username
FROM
    user_friends FRIEND, users USERS
WHERE 
    FRIEND.friend_one IN (SELECT friend_two FROM user_friends WHERE friend_one = :id)
    AND FRIEND.friend_two NOT IN (SELECT friend_two FROM user_friends WHERE friend_one = :id)
    AND NOT FRIEND.friend_two = :id
GROUP BY possible_friend

用户

+------------+------------------+
|     id     |     username     |
+------------+------------------+
|     10     |       Josh       |
+------------+------------------+
|     20     |     Steward      |
+------------+------------------+
|     30     |      Fenton      | 
+------------+------------------+

用户朋友

+------------+------------+------------+------------+
| friend_id  | friend_one | friend_two |    Role    |
+------------+------------+------------+------------+
| ramdom_id  |     10     |     10     |     me     +
+------------+------------+------------+------------+
| ramdom_id  |     20     |     20     |     me     +
+------------+------------+------------+------------+
| ramdom_id  |     10     |     20     |   friend   +
+------------+------------+------------+------------+
| ramdom_id  |     20     |     30     |   friend   +
+------------+------------+------------+------------+

friend_one = 10 (Josh)      -> follows -> friend_two = 20 (Steward)
friend_one = 20 (Steward)   -> follows -> friend_two = 30 (Fenton)

var_dump($查询); 显示以下文本。

Array ( [possible_friend] => 30 [possible_username] => STEWARD )

var_dump 中的错误是我已经关注 Steward,而 Steward 的 id 为 (20)。我想展示的是

Array ( [possible_friend] => 30 [possible_username] => FENTON )

由于 Fenton 有一个 id(30)并且Josh(10)登录的人没有关注 Fenton。

如果Josh(10)已登录,则建议JOSH关注,Fenton(30)因为Steward(20)关注Fenton(30)Josh(10)没有。

当这个查询结束时,它的目的是建议我的朋友的朋友供用户关注,如上所述。

我如何使用 GROUP BY 来确保被建议的用户打印了正确的用户名,正如我在 FENTON 的 var_dump 中解释的那样。截至目前,它正在检索我已经关注的用户的随机用户名,而不是查询中的“AS possible_friends”。


4

2 回答 2

1

问题是您的查询中实际上没有对USERS要返回的行施加任何限制,因此您将 的每个相关行连接USER_FRIENDS到 的所有USERS,然后将其留给GROUP BY任意选择一个。

最好的解决办法是改变这个:

FROM
    user_friends FRIEND, users USERS

对此:

FROM user_friends friend
JOIN users
  ON users.id = friend.friend_two

指定您正在专门寻找与相关行匹配的USERS行。idfriend_twoUSER_FRIENDS

于 2013-09-10T01:52:26.863 回答
0

这是您可能会考虑的另一种方法:

SELECT FRIEND_NAME.username, P_FRIEND_NAME.username
FROM user_friends FRIENDS 
INNER JOIN user_friends P_FRIENDS on FRIENDS.friend_one = P_FRIENDS.friend_two
INNER JOIN users FRIEND_NAME on FRIENDS.friend_two = FRIEND_NAME.id
INNER JOIN users P_FRIEND_NAME on P_FRIENDS.friend_one = P_FRIEND_NAME.id
WHERE FRIENDS.friend_one <> P_FRIENDS.friend_one
and FRIENDS.friend_two <> P_FRIENDS.friend_two

结果:芬顿 | 乔什

于 2013-09-10T03:58:29.263 回答