2012-04-27 78 views
2

我正在使用以下系统的Twitter类型。我加入了两个表格,用户和关注者,以获取关注者表中用户的姓氏和名字。然后我在followers表上运行一个内部连接来捕捉关注者和朋友关系。我将跟随者(谁跟随你),跟随(谁跟随)和朋友(彼此跟随)展示结果。twitter风格的追随者/以下/朋友sql查询

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

谢谢。

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 

回答

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

使用此方法很容易获得关于跟随你的用户的信息,但可以推导出他们是否跟随你。非常高效并在一个查询中完成;只需要重新架构。 – philwinkle 2012-04-27 21:09:24

+0

如果你想要一个快速入门 - 这是一个模型在一个pastie:http://pastebin.com/4UPwAYPX – philwinkle 2012-04-27 21:12:59

+0

谢谢你。你建议的表格设置是我目前的设置。我要去尝试这个新的查询,很快就会回复。 – chowwy 2012-04-27 21:26:18

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

感谢你为这个。我现在要尝试一下。 – chowwy 2012-04-27 21:26:59

+0

我提高了你的答案;这个查询很好地识别朋友朋友。我选择了另一个答案,因为它允许我从一个查询中识别追随者和朋友。 – chowwy 2012-04-27 23:41:44

+0

我的意思是,识别朋友,而不是朋友的朋友很有效。 – chowwy 2012-04-27 23:47:34