2011-12-19 76 views
-1

我正在建立一個php/mysql論壇,它有兩個表格。第一個是主線程表,第二個是回覆表,其結構是這樣的(省略一些與這個問題無關的列,如'title','body_text'等)。選擇論壇主題和最新回覆

  1. thread_table 色譜柱:

    • ID(INT,主鍵)
    • USER_ID(INT)
    • 刪除(布爾/ tiny_int)
    • date_posted(日期時間)
  2. reply_table 個色譜柱:

    • ID(INT,主鍵)
    • linked_to(INT)
    • USER_ID(INT)
    • 刪除(布爾/ tiny_int)
    • date_posted(日期時間)

我真的卡在我的SQL,我想選擇所有'線程',最新'回覆'每個線程的刪除不等於1,也是每個線程的回覆總數,其中刪除不等於1.另外,我還希望從我的用戶表中選擇「user_name」,其中線程/回覆' user_id'等於用戶表中的相同ID。

+0

你想用1查詢這個(因爲這將是凌亂的,如果不是不可能的話)?可能更好地解決這個小碎片。 – 2011-12-19 09:47:49

+0

我很樂於提供建議,不需要使用一個大的混亂查詢,我很樂意將它分解爲兩個,並循環通過第一個結果或任何需要的東西! – 2011-12-19 10:04:42

回答

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

嘿,那太棒了!非常感謝,明天我會玩一玩(在這裏遲到) – 2011-12-19 11:42:36

+0

任何運氣?這是否解決了你的問題?如果是這樣,請接受它作爲答案:) – GuZzie 2011-12-20 08:30:10