繁体   English   中英

如何使用2个SQL查询检索包含所有注释的所有帖子

[英]How to retrieve all posts with all comments using 2 SQL queries

我正在尝试创建一个包含帖子列表的页面,并在每个帖子下面发布属于该帖子的所有评论。 最初我想使用一个查询来使用SQL的JOIN检索所有帖子+注释,但我发现无法检索具有多个注释的帖子。 它仅显示每个帖子最多为1条评论的帖子,或者只是根据评论的数量多次显示帖子。

在这个相关的问题,有人谈到使用2个查询: 如何只用一个SQL查询打印帖子和评论

但是我该怎么做?

我有帖子的查询和while循环,但我显然不想为该循环中的每个帖子运行查询。

$getPost = mysql_query('SELECT p.post_id,
                               p.user_id,
                               p.username,
                               p.content
                        FROM post p
                        ORDER BY p.post_id DESC');

while($row = mysql_fetch_array($getPost)) 
{ 
... 
}

表结构(回复是用于存储注释的表):

POST (post_id (primary key), user_id, username, content, timestamp)
REPLY (reply_id (primary key), post_id, username, reply_content, timestamp)

您可以在单个查询中执行此操作,如果原始帖子中的数据量很小,则可以

$getPost = mysql_query('SELECT
  p.*,
  r.reply_id, r.username r_username, r.reply_content, r.timestamp r_timestamp
  FROM post p
    left join reply r
  ORDER BY p.post_id DESC'
);

$posts = array();
$last_id = 0;
while($row = mysql_fetch_array($getPost)) 
{ 
  if ($last_id != $row['post_id']) {
    $posts[] = array(
      'post_id' => $row['post_id'],
      'user_id' => $row['user_id'],
      'username' => $row['username'],
      'content' => $row['content'],
      'timestamp' => $row['timestamp'],
      'comments' => array()
    );
  }

  $posts[sizeof($posts) - 1]['comments'][] = array(
    'reply_id' => $row['reply_id'],
    'username' => $row['r_username'],
    'reply_content' => $row['reply_content'],
    'timestamp' = $row['r_timestamp']
  );
}

否则,将其分成两个查询,如下所示:

$getPost = mysql_query('SELECT
  p.*,
  FROM post p
  ORDER BY p.post_id DESC'
);

$rows = array();
$ids = array();
$index = array();
while($row = mysql_fetch_assoc($getPost)) {
  $row['comments'] = array();
  $rows[] = $row;
  $ids[] = $row['post_id'];
  $index[$row['post_id']] = sizeof($rows) - 1;
}

$getComments = mysql_query('select r.* from replies r where r.post_id in ("'
  . join('","', $ids)
  . '")');
while ($row = mysq_fetch_assoc($getComments)) {
  $rows[$index[$row['post_id']]]['comments'][] = $row;
}

... 或类似的东西。 任何一个选项都允许您使用WHERE子句乱丢您的第一个查询,等等。 第二种方法的优点是您不会为每条评论重新传输原始帖子数据!

为了获得那些没有评论的帖子,你需要使用LEFT OUTER JOIN 在这种情况下,第一个表中没有第二个表中任何相应行的任何行将与由空值组成的行配对。

SELECT *  FROM posts
LEFT OUTER JOIN comments ON posts~post_id = comments~post_id;

顺便说一句:还有一个RIGHT OUTER JOIN 当你使用它时,你会收到所有评论,包括父帖以某种方式丢失的评论,但没有评论的帖子。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM