-6

在 mysql 中关注/订阅其他用户的用户的下表中(在“关注”表中相关),我想获取给定用户订阅的用户发布的帖子:

表1:跟随

|-----------------------------------------|
|   id      |    uid     |    friends     |
|-----------------------------------------|
|   1       |     1      |      2         |
|   2       |     1      |      3         |
|   3       |     2      |      1         |
|-----------------------------------------|

表2:员额

|-----------------------------------------------------|
|   id  |  uid   |    posts    |  date                |
|-----------------------------------------------------|
|   1   |   1    |   hai..     |  2013-07-08 01:56:09 |
|   2   |   5    |   awesome   |  2013-07-08 11:45:50 |
|   3   |   2    |   greate!!  |  2013-07-09 21:13:29 |
|   4   |   3    |   himm..    |  2013-07-10 12:06:10 |
|   5   |   2    |   super..   |  2013-07-10 14:50:09 |
|-----------------------------------------------------|

表 3:用户

|---------------------------|
|   uid     |     name      |
|---------------------------|
|   1       |     ram       |
|   2       |     syed      |
|   3       |     seeta     |
|---------------------------|

例如:给定 uid 1 的用户,同时关注 uid 2 和 3 的用户,我想显示我的帖子和关注的最新帖子

结果将如下所示:

   2 posted   
   super..  
     time:2013-07-10 14:50:09

   3 posted   
   himm..  
     time:2013-07-10 12:06:10

   2 posted   
   greate!!  
     time:2013-07-09 21:13:29

   1 posted   
   hai..  
     time:2013-07-08 01:56:09
4

2 回答 2

1

假设您的用户 ID 为 5:

SELECT * FROM posts WHERE posts.uid IN (SELECT follow.friends FROM follow WHERE follow.uid=5)

或者您可以加入表格:

SELECT posts.* FROM posts JOIN follow ON posts.uid = follow.friends WHERE follow.uid=5

如果您还想查看自己的帖子:

SELECT * FROM posts WHERE posts.uid=5 OR posts.uid IN (SELECT follow.friends FROM follow WHERE follow.uid=5)
于 2013-07-10T09:13:46.340 回答
0

我不确定您的表是否在 sql 中,但如果是,我认为获取所需数据的最佳方法是使用 LEFT JOIN,如下所示:

SELECT * FROM follow
JOIN posts
ON (follow.friends = posts.uid OR follow.uid = posts.uid)
WHERE follow.uid = {user_uid}

其中 {user_id} 是您想要的用户 ID。

如果是这种情况,请进一步查看连接(fe at tizag)和左连接。

于 2013-07-10T09:15:21.670 回答