我假設你在你的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 />';
}
你想用1查詢這個(因爲這將是凌亂的,如果不是不可能的話)?可能更好地解決這個小碎片。 – 2011-12-19 09:47:49
我很樂於提供建議,不需要使用一個大的混亂查詢,我很樂意將它分解爲兩個,並循環通過第一個結果或任何需要的東西! – 2011-12-19 10:04:42