选择论坛帖子和最新回复

时间:2011-12-19 09:41:15

标签: php mysql

我正在构建一个php / mysql论坛,它有两个表。第一个是主“线程”表,第二个是回复表,结构本身(省略了与此问题无关的一些列,例如'title','body_text'等)。

  1. thread_table 列:

    • id(int,primary key)
    • user_id(int)
    • 已删除(bool / tiny_int)
    • date_posted(datetime)
  2. reply_table 列:

    • id(int,primary key)
    • linked_to(int)
    • user_id(int)
    • 已删除(bool / tiny_int)
    • date_posted(datetime)
  3. 我真的坚持我的sql,我想选择所有'线程',每个线程的最新'回复',其中删除不等于1,以及每个删除的线程的回复总数最重要的是,我还想从我的users表中选择'user_name',其中thread / reply'user_id'等于用户表中的相同id。

1 个答案:

答案 0 :(得分:1)

我假设你在你的id上使用auto_increment,所以最高的数字总是最后的回复。

请注意,以下代码未经过测试,但它应该会帮助您一路走来! 我已经评论了这些步骤,以便您可以看到发生了什么。希望这能帮到你!

//Fetch the thread headers and put result in array
$get_header = "SELECT thread.id, user.user_name, thread.date_posted FROM thread_table thread, user_table user WHERE thread.user_id = user.user_id AND thread.deleted != 1;";
    $Rget_header = mysql_query($get_header) or die(mysql_error());

    while($row_get_header = mysql_fetch_array($Rget_header)){
            $arr_get_header[] = array( "thread_id"   => $row_get_header['id'],
                                       "username"    => $row_get_header['user_name'],
                                       "date_posted" => $row_get_header['date_posted']
                                      );
    }

//Loop through the header array 
for ($c = 0; $c < count($arr_get_header); $c++){

    //Fetch the count
    $count_replies = "SELECT COUNT(id) as reply_count FROM reply_table WHERE linked_to = '".$arr_get_header[$c]['thread_id']."';";
        $Rcount_replies = mysql_query($count_replies) or die(mysql_error());

        $num_count_replies = mysql_num_rows($Rcount_replies);

            if ($num_count_replies == 1) {
                $obj_get_reply = mysql_fetch_object($Rcount_replies);
            }

    //Get last reply
    $get_reply = "SELECT MAX(reply.id) as reply_id, user.user_name, reply.date_posted FROM reply_table reply, user_table user WHERE reply.user_id = user.id AND reply.deleted != 1 AND reply.linked_to = '".$arr_get_header[$c]['thread_id']."' ORDER BY reply_id;";
        $Rget_reply = mysql_query($get_reply) or die(mysql_error());

        $num_get_reply = mysql_num_rows($Rget_reply);

            if ($num_get_reply == 1) {
                $obj_get_reply = mysql_fetch_object($Rget_reply);
            }

    //Echo result
    echo 'Thread id: '.$arr_get_header[$c]['thread_id'].'<br />';
    echo 'Last reply id: '.$obj_get_reply->reply_id.'<br />';
    echo 'Reply count: '.$obj_count_replies->reply_count.'<br />';

}