MySQL QUERY:使用ORDER BY加入多个表

时间:2013-09-10 01:31:26

标签: php mysql sql pdo

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      | 
+------------+------------------+

user_friends

+------------+------------+------------+------------+
| 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”。


2 个答案:

答案 0 :(得分: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与相关id行的friend_two匹配的USER_FRIENDS行。

答案 1 :(得分: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

结果: 芬顿|约什