twitter风格的关注者/关注/朋友sql查询

时间:2012-04-27 20:41:04

标签: mysql

我正在开发一种推特类型的关注系统。我正在加入两个表,用户和关注者,以获取关注者表中的用户的名字和姓氏。然后我在追随者表上运行内部联接以捕获追随者和朋友的关系。我将结果显示为关注者(跟随你的人),跟随(跟随你的人)和朋友(相互跟随)。

通过下面的查询,我只能显示想要看到他们的朋友的用户的名字。我想显示用户的FRIENDS,而不是用户自己的名字,但无法弄清楚如何让users表做双重任务 - 也就是说,告诉我用户的名字和名字他们的朋友,或者只是朋友的名字。

感谢。

SELECT users.id, users.firstname, users.lastname, followers.follower_user_id, followers.followee_user_id
            FROM users
            JOIN followers ON followers.follower_user_id = users.id
            INNER JOIN followers ff ON followers.followee_user_id = ff.follower_user_id AND followers.follower_user_id = ff.followee_user_id

2 个答案:

答案 0 :(得分:7)

我相信您的架构需要一个联合表来汇集您需要的信息;在多个表中执行此操作可能更有效。从用户维护具有(可能的)重复信息的单独的关注者表也可能是不希望的。更有效的架构是:

mysql> select * from users;
+-----+------------+---------+
| uid | fname      | lname   |
+-----+------------+---------+
|   1 | Phillip    | Jackson |
|   2 | Another    | Name    |
|   3 | Some Crazy | User    |
|   4 | Nameless   | Person  |
+-----+------------+---------+
4 rows in set (0.00 sec)


mysql> select * from follows;
+---------+-----------+
| user_id | follow_id |
+---------+-----------+
|       1 |         4 |
|       2 |         3 |
|       3 |         2 |
|       4 |         2 |
+---------+-----------+
4 rows in set (0.00 sec)

然后您的查询将如下所示:

select users.uid,
users.fname,
users.lname,
u.uid,
u.fname,
u.lname from users
inner join follows f on (f.user_id=users.uid)
inner join users u on (u.uid=f.follow_id)

返回:

mysql> select users.uid,
    -> users.fname,
    -> users.lname,
    -> u.uid,
    -> u.fname,
    -> u.lname from users
    -> inner join follows f on (f.user_id=users.uid)
    -> inner join users u on (u.uid=f.follow_id);
+-----+------------+---------+-----+------------+--------+
| uid | fname      | lname   | uid | fname      | lname  |
+-----+------------+---------+-----+------------+--------+
|   1 | Phillip    | Jackson |   4 | Nameless   | Person |
|   4 | Nameless   | Person  |   2 | Another    | Name   |
|   2 | Another    | Name    |   3 | Some Crazy | User   |
|   3 | Some Crazy | User    |   2 | Another    | Name   |
+-----+------------+---------+-----+------------+--------+
4 rows in set (0.00 sec)

答案 1 :(得分:2)

SELECT  u.id, u.first_name, u.last_name, uf.id, uf.first_name, uf.last_name
FROM    users u
JOIN    followers f
ON      f.follower_user_id = u.id
JOIN    followers ff
ON      (ff.followee_user_id, ff.follower_user_id) = (f.follower_user_id, f.followee_user_id)
JOIN    users uf
ON      uf.id = f.followee_user_id