2011-12-19 9 views
-1

私はphp/mysqlフォーラムを構築しており、2つのテーブルがあります。最初はマスターの 'スレッド'テーブルで、2番目は返信テーブルです。構造体はそのようなものです( 'title'、 'body_text'などのこの質問に関係のないいくつかの列は省略します)。フォーラムスレッドと最新の回答を選択

  1. thread_table カラム:

    • ID(INT、プライマリキー)
    • USER_ID(INT)
    • 削除(BOOL/tiny_int)
    • date_posted(日時)
  2. reply_table カラム:

    • ID(INT、プライマリキー)
    • linked_to(INT)
    • USER_ID(INT)
    • 削除(BOOL/tiny_int)
    • date_posted(日時)

私は本当に私のSQLに固執しています、私はすべての 'スレッド'を選択したい、最新の '返信'削除されていないスレッドが1に等しくない場合、削除されたスレッドが1に等しくない場合の返答の合計数も表示されます。また、ユーザーのテーブルから 'thread_name/reply' user_id 'はユーザーテーブルの同じIDと同じです。

+0

これに対して1つのクエリを使用しますか(これは不可能ではないにしても、面倒なので)。おそらくこれを小さなもので取り組む方が良いでしょう。 –

+0

私は提案には開放されています。大規模で面倒なクエリを使用する必要はありません。最初の結果を取って2つに分割してループしてもよかったです。 –

答えて

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 />'; 

} 
+0

ねえ、それは素晴らしいです!それに感謝して、私は明日(ここに遅れて)遊びに行くよ。 –

+0

運がいい?これで問題は解決しましたか?もしそうなら、答えとしてそれを受け入れてください:) – GuZzie

関連する問題