2011-05-09 62 views
0

試圖讓我的結果按月排序並顯示在表中。我哪裏錯了?MySQL在PHP腳本中按月排序

查詢:

mysql_query("SELECT COUNT(*), DATE_FORMAT(DATE(`dPostDateTime`), '%W, %b, %e') AS `day`, DATE(`dPostDateTime`) AS 'date' FROM `tblQA` WHERE cCategory IN ('Football','Baseball','Basketball','Hockey') AND dPostDateTime >= '2010-08-01' AND dPostDateTime <= '2011-07-31' GROUP BY `month`"); 

PHP代碼:

while($row = mysql_fetch_assoc($monthlyQ)) 
{ 
$printedRecords1++; 
echo "<tr class='forum'>"; 
echo "<td class='forum'>" . $row['month'] . "</td>"; 
echo "<td class='forum'>" . $row['COUNT(*)'] . "</td>"; 
echo "</tr>"; 
} 
for ($i = $printedRecords1; $i < $Print; $i++) { 
echo "<tr class='forum'>"; 
echo "<td class='forum'>&nbsp;</td>"; 
echo "<td class='forum'>&nbsp;</td>"; 
echo "</tr>"; 
} 
echo "</table></td><td>"; 
+1

爲什麼不按月查詢本身排序? – 2011-05-09 21:48:56

回答

0

當你說你正在嘗試時,我假設按月排序,你只是想知道每個月有多少行,因爲這看起來是什麼你的代碼在做什麼。

如果你的表中實際上有一個'月'字段,那麼你的SQL很好,除了你從不真正選擇該字段,所以$row['month']不應該與該SQL有一個值。
所以,你需要選擇它象下面這樣:

mysql_query("SELECT COUNT(*), `month`, DATE_FORMAT(DATE(`dPostDateTime`), '%W, %b, %e') AS `day`, DATE(`dPostDateTime`) AS 'date' FROM `tblQA` WHERE cCategory IN ('Football','Baseball','Basketball','Hockey') AND dPostDateTime >= '2010-08-01' AND dPostDateTime <= '2011-07-31' GROUP BY `month`"); 

如果你沒有一個「月」字段(,只是有日期字段,給出不應該是工作這將意味着你的查詢)你需要以與你的'一天'類似的方式創建它。

mysql_query("SELECT COUNT(*), MONTH(`dPostDateTime`) AS `month`, DATE_FORMAT(DATE(`dPostDateTime`), '%W, %b, %e') AS `day`, DATE(`dPostDateTime`) AS 'date' FROM `tblQA` WHERE cCategory IN ('Football','Baseball','Basketball','Hockey') AND dPostDateTime >= '2010-08-01' AND dPostDateTime <= '2011-07-31' GROUP BY `month`"); 

然後,如果你希望你的結果,以按月訂購一樣,所以表雲在cronological順序,你想添加在那裏ORDER BY month還有,假設它的存在(如例如1)或者你正在創建它(如例2)。

+0

如果我使用MONTHNAME,我該如何按月訂購? – BigMike 2011-05-09 22:26:56

+0

你真的可以'僅僅通過dPostDataTime'命令,它只是將你所有的行都排序,因爲你只是按月分組並不重要。可能是最簡單的解決方案,無論如何都能正常工作。 – John 2011-05-09 22:36:44

0

如果你希望他們按月排序,那麼你需要添加

ORDER BY `month` 

到SQL

+0

更喜歡'ORDER BY MONTH(dPostDateTime)' - 查詢示例中沒有月份字段。 – 2011-05-09 21:56:59

+0

@Marc B:你可能是對的。有一個'GROUP BY month'和一個'$ month'變量給我扔了。 – 2011-05-09 21:58:56