我相信您的架构需要一个联合表来组装您需要的信息;在多个表中执行此操作可能更有效。使用来自用户的(可能)重复信息来维护单独的关注者表也可能是不可取的。更有效的模式是:
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)