4

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

通过下面的查询,我只能显示想见他们朋友的用户的姓名。我想显示用户的 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
4

2 回答 2

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)
于 2012-04-27T21:08:00.087 回答
3
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
于 2012-04-27T20:54:59.413 回答