如何查询用户的所有朋友的帖子(存储在3个MySQL表之间)?

时间:2015-11-01 18:39:29

标签: php mysql mysqli inner-join

所以我将用户信息,用户发布的内容和朋友都放在不同的表格中。

示例数据:

用户:

id    username      email
1     userA         myemail@testa.com
2     userB         myemail@testb.com
3     userC         myemail@testc.com

USER_CONTENT

id    user_id      date                     text
1     1             2015-09-12 00:24:08     content here
2     2             2015-09-11 00:24:08     more content here a
3     1             2015-09-10 00:24:08     more content here b
4     3             2015-09-05 00:24:08     more content here c

朋友

id    user_id_1  user_id_2
1     1          2
2     2          3
3     2          4

user表存储有关特定用户的信息,user_content存储该用户发布的内容以及friends商店'朋友'用户之间的关联。

我的问题是,如何查询此数据以获取按日期排序的特定用户的所有朋友的user_content?目前,我遍历特定用户的每个朋友:

$stmt = $mysqli->prepare("SELECT user_id_1, user_id_2 FROM friends WHERE user_id_1 = ? OR user_id_2 = ?");
$stmt->bind_param("ii", $userID, $userID);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($db_user_id_1, $db_user_id_2);
while ($stmt->fetch()) {
    //Work out which is the user, and which is the friend
    $friendID = $db_user_id_1;
    if ($userID == $db_user_id_1) {
        $friendID = $db_user_id_2;
    }

    //Load latest 10 user_content for each user, store in memory and sort by date
}
$stmt->close();

但这可能在一个MySQL查询中吗?循环遍历每个朋友然后按日期排序的开销似乎有点过分。我只想为特定用户的所有朋友提供最新的30 user_content

3 个答案:

答案 0 :(得分:1)

从联系朋友的user_content内部选择,抓取user_content记录不属于当前用户但当前用户是其中一个朋友的用户的所有内容......或者只是查看查询

修改:忘记添加最近30个帖子的限制

SELECT
     uc.user_id AS friend_user_id
    ,u.username AS friend_username
    ,u.email AS friend_email
    ,uc.date
    ,uc.text
FROM user_content uc
INNER JOIN friends f ON uc.user_id IN (f.user_id_1,f.user_id_2)
INNER JOIN user u ON uc.user_id = u.id
WHERE uc.user_id != ? AND ? IN (f.user_id_1, f.user_id2)
ORDER BY date DESC
LIMIT 30;

答案 1 :(得分:0)

您需要的是LEFT JOIN

SELECT u.`username`, u.`email`, c.`text`, c.`date`
FROM user AS u
LEFT JOIN friends AS f ON f.`user_id_1` = u.`id`
LEFT JOIN user_content AS c ON c.`user_id` = f.`user_id_2`
WHERE u.`username` = 'userA'
ORDER BY c.`date` ASC
LIMIT 0,30

这会根据您的条件连接表格friendsuseruser_content

答案 2 :(得分:0)

我没有完全实现你的目标。

但是我的方法是获取某些?用户的朋友的所有内容:

http://sqlfiddle.com/#!9/fb40e/2

SELECT uc.*
FROM user_content uc
INNER JOIN friends f
ON f.user_id_2 = uc.user_id
  AND f.user_id_1 = ?

更新如果您不确定哪个字段是uder_id哪个字段friend_id,则可以使用OR对其进行转换:

http://sqlfiddle.com/#!9/fb40e/3

SELECT uc.*
FROM user_content uc
INNER JOIN friends f
ON (f.user_id_2 = uc.user_id
  AND f.user_id_1 = ?)
  OR (f.user_id_1 = uc.user_id
  AND f.user_id_2 = ?)