简体   繁体   English

MySQL在PHP脚本中按月排序

[英]MySQL Sort by Month in PHP script

Trying to get my results sorted by month and displayed in a table. 试图让我的结果按月排序并显示在表格中。 Where am I going wrong? 我要去哪里错了?

Query: 查询:

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 Code: 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>";

If you want them sorted by month, then you need to add 如果要按月对它们进行排序,则需要添加

ORDER BY `month`

to your SQL 到你的SQL

I assume when you say you're trying to sort by month, you just mean you're trying to figure out how many rows are in each month, since that looks what what your code is doing. 我假设当您说要按月排序时,您的意思只是想弄清楚每个月有多少行,因为这看起来像您的代码在做什么。

If you actually have a 'month' field in your table, then your SQL is fine, except that you never actually select that field, so $row['month'] shouldn't have a value with that SQL. 如果您的表中确实有一个“ month”字段,那么您的SQL很好,除非您从未实际选择该字段,因此$row['month']不应与该SQL一起使用。
So you need to select it like below: 因此,您需要像下面这样选择它:

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`");

If you don't have a 'month' field (and just have the date field, which would mean your query as given shouldn't be working) you need to be creating that in a similar way as your 'day'. 如果您没有“月”字段(而只有日期字段,这意味着给定的查询不起作用),则需要以与“天”类似的方式进行创建。

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`");

Then, if you want your results to be ordered by the month as well, so the table goes in a cronological order, you'd want to add ORDER BY month in there as well, assuming it exists (as in example 1) or you're creating it (as in example 2). 然后,如果您还希望按月对结果进行排序,因此表按年代顺序排列,那么您还希望在其中也添加ORDER BY month (假设其存在)(如示例1中所示),或者正在创建它(如示例2所示)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM