SQL内部加入新闻Feed

时间:2013-12-12 02:34:08

标签: php mysql sql inner-join

我在语句的内部联接方面遇到了一些麻烦。我正在尝试从其新闻Feed中的用户朋友列表中获取所有“帖子”。我试图通过获取用户为initiator_user_id的所有帖子并从friend_user_id获取所有帖子然后我想获取来自initiator_user_id的所有帖子,其中用户的id是friend_user_id。

以前这可行,但它只获取用户为initiator_user_id的帖子:

$wallsql= $conn->prepare('SELECT * FROM activity f INNER JOIN wp_bp_friends n2 ON n2.friend_user_id=f.user_id WHERE n2.initiator_user_id=:userid ORDER BY datetime DESC LIMIT 8');

用户ID 24可以看到用户ID 22的“帖子”,例如创建22的帐户并更新其状态。它需要做的是让userid 22也看到userid 24的更新。现在它是单方面的。我认为以下内容可以实现两种方式:

$wallsql= $conn->prepare('SELECT * FROM activity f INNER JOIN wp_bp_friends n1 ON (n1.initiator_user_id=f.user_id) INNER JOIN wp_bp_friends n2 ON (n2.friend_user_id=f.user_id) WHERE (n1.friend_user_id=:userid) OR (n2.initiator_user_id=:userid) ORDER BY datetime DESC LIMIT 8'); 
$wallsql->bindParam(':userid', $_SESSION['uid']);
$wallsql->execute();

以下是表格及其设置方法。

wp_bp_friends table:

id     initiator_user_id     friend_user_id     is_confirmed     is_limited     date_created
11            24                    22                1               0          2013-12-11 11:17:26




Activity table:

ID     user_id                type                       component     filetype     group_id            content                     datetime
15        22             accountcreated                     NULL           NULL            0                NULL                2013-12-11 11:17:26
15        22                   status                       NULL           NULL            0           Hello World!          2013-12-11 11:17:26
15        24            accountcreated                      NULL           NULL             0               NULL                2013-12-11 11:17:26
15        24                   status                       NULL           NULL            0             Whats up            2013-12-11 11:17:26

1 个答案:

答案 0 :(得分:1)

这可能有效:

SELECT * 
FROM   activity f 
       INNER JOIN wp_bp_friends n2 
               ON n2.friend_user_id = f.user_id 
WHERE  n2.initiator_user_id = :userid 
UNION ALL 
SELECT * 
FROM   activity f 
       INNER JOIN wp_bp_friends n2 
               ON n2.initiator_user_id = f.user_id 
WHERE  n2.friend_user_id = :userid 
ORDER  BY datetime DESC 
LIMIT  8