-1

最常见的第一次尝试是(伪代码):

posts = SELECT * FROM posts

for each (post in posts) {
    post[comments] = SELECT * FROM comments WHERE post_id = {post[id]}
}

但是最好有 JOIN,对吧?(或不?告诉我)所以:

posts = SELECT * FROM posts JOIN comments ON comments.post_id = posts.id

所以结果将是这样的:

post_id | post | comment_id | comment
===============================================
1       | foo  | 1          | nice foo
1       | foo  | 2          | dont like ur foo
2       | bar  | 3          | bar is better

如何转换为这个?

array(
    array(
        'id' => 1,
        'post' => 'foo',
        'comments' => array(
            array('id' = 1, 'comment' => 'nice foo'),
            array('id' = 2, 'comment' => 'dont like ur foo'),
        )
    ),
    array(
        'id' => 2,
        'post' => 'bar'
        'comments' => array(
            array('id' = 1, 'comment' => 'bar is better')
        )
    ),
);

谢谢!

4

2 回答 2

4

您只需遍历结果集并适当地构建数组...推测 post_id 是主键,因此是唯一的,因此您可以将其用作数组键并检查是否已创建帖子,然后添加评论数据,或创建一个帖子,然后添加评论数据。

例如在伪 php 代码中:

$posts = array();
while(false !== ($row = whatever_assoc_fetch_func($result))) {

   $id = $row['post_id'];
   $commentId = $row['comment_id'];

   if(!isset($posts[$id])) {
      $posts[$id] = array(
         'id' => $id,
         'post' => $row['post'],
         'comments' => array()
      );
   }

   $posts[$id]['comments'][$commentId] = array(
       'comment_id' => $commentId,
       'comment' => $row['comment']
   );

}
于 2013-07-02T19:28:32.257 回答
0

您绝对应该JOIN尽可能使用 's 以及明确选择您的列。示例(未测试):

SELECT 
  tbl1.a AS tbl1_a,
  tbl1.b AS tbl1_b,
  tbl1.c AS tbl1_c,
  tbl2.a AS tbl2_a,
  tbl2.b AS tbl2_b,
  tbl2.c AS tbl2_c
FROM tbl1
INNER JOIN tbl2 ON tbl2.parent_id = tbl1.id

连接的类型很多,都可以在这里学习:http: //www.codeproject.com/Articles/33052/Visual-Representation-of-SQL-Joins

在此处输入图像描述

于 2013-07-02T19:21:51.107 回答