0

我有这种情况。

我输入 $groupid="1";

主表

----------------------
| groupid  |  postid  |
|---------------------|
|       1  |       1  |
|       2  |       2  |
|       1  |       3  |

$query = "SELECT postid FROM `mainl` WHERE groupid='$groupid'";
$result = mysql_query($query);

// a group of postids belonging to that groupid which should hold [1, 3] for groupid=1
while($row = mysql_fetch_array($result)) {
    $postids[] = $row["postid"];
}

第二张桌子

-------------------------------------------
|  postid  |  commentid  |     comment    |
-------------------------------------------
|       1  |          1  |   testing 1    |
|       1  |          2  |   testing 2    |
|       1  |          3  |       what?    |
|       2  |          1  |       hello    |
|       2  |          2  | hello world    |
|       3  |          1  |      test 3    |
|       3  |          2  |       begin    |
|       3  |          3  |        why?    |
|       3  |          4  |       shows    |


$query = "SELECT * FROM `second`";
$result = mysql_query($query);

while ($row = mysql_fetch_array($result)) {
    if (in_array($row["postid"], $postids)) {
        $comments[$row["postid"]] = $row["comment"];

但是我应该如何处理评论
我希望 postid 数组[1,3]和我的评论数组是 [commentid: comment] [1:testing1, 2: testing2, 3: what?]forpostid=1

[1:test3, 2:begin, 3: why? 4:shows]forpostid=3

应该如何安排所有这些评论与commentid和postid相关联?

4

2 回答 2

1

首先,我会遵循 rokdd 的建议并进行 1 次查询

SELECT  m.groupid , s.postid, s.commentid, s.comment FROM `main1` m JOIN `second` s USING (postid) where m.groupid = 1

然后我会做一个多维数组

while ($row = mysql_fetch_array($result))
    $groups[$row['groupid'][$row['postid']][$row['commentid']=$row['comment'];

然后遍历数组

foreach($groups as $group)    
    foreach($group as $post)
        foreach($post as $comment)
           echo $comment;

这也将跟踪组(如果您想选择超过 1 个组。如果您不关心组,只需删除数组的第一部分。

while ($row = mysql_fetch_array($result))
    $posts[$row['postid']][$row['commentid']=$row['comment'];


    foreach($posts as $post)
        foreach($post as $comment)
           echo $comment;
于 2012-06-13T02:11:33.837 回答
0

我想在 sql 中使用 join,这样你就会有一个语句:

SELECT * FROM second as second_tab LEFT join main as main_table ON main_table.post_id=second_table.post_id WHERE main_table.group_id="3"

现在还没有经过测试,但这是解决您的一些问题的一种方法!

于 2012-06-12T20:33:44.667 回答