我正在使用ChartJS为票务应用程序构建一些图表。
我要做的是在MySQL数据库中查询为当月的第1周,第2周,第4周和第4周创建的门票数量。
$month_num_tickets = array();
for ($x=0;$x<=30;$x=$x+6) {
$from = date("Y-m-d 00:00:00",strtotime('first day of this month +'.$x.' days', time()));
$to = date("Y-m-d 23:59:59",strtotime($from, time()));
$get = mysql_query("SELECT id FROM tickets WHERE date_created BETWEEN UNIX_TIMESTAMP('$from') AND UNIX_TIMESTAMP('$to') AND assigned_tech_uid='$uid'") or die(mysql_error());
$month_num_tickets[] = mysql_num_rows($get);
}
不确定如何设置循环...
答案 0 :(得分:3)
您可以在单个查询中获得一个漂亮的整洁计数:
SELECT
CEIL(DAYOFMONTH(FROM_UNIXTIME(date_created)) / 7) AS week_of_month,
COUNT(id) AS tickets_per_week
FROM tickets
WHERE YEAR(FROM_UNIXTIME(date_created)) = ?
AND MONTH(FROM_UNIXTIME(date_created)) = ?
GROUP BY `week_of_month`
ORDER BY `week_of_month` ASC
请注意,如果您使用了原生日期时间或时间戳文件,则可以摆脱所有这些FROM_UNIXTIME
次转化。这基于&#34;周&#34;是本月的前7天,而不是基于一周中的特定日期。如果你想要它基于固定周(根据星期日或星期六等),你可以在SELECT中使用WEEK()
函数。
这可能是这样的:
SELECT
WEEK(FROM_UNIXTIME(date_created), 0) AS week_number,
COUNT(id) AS tickets_per_week
FROM tickets
WHERE YEAR(FROM_UNIXTIME(date_created)) = ?
AND MONTH(FROM_UNIXTIME(date_created)) = ?
GROUP BY `week_number`
ORDER BY `week_number` ASC
这里week_number
将是0-53之间的值,并且除了作为聚合手段之外,不一定具有任何显示意义。我使用模式0表示WEEK()
functoin,因为这指定了周日周六。您可以在此处查看定义并确定最适合您的模式:http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_week
这些查询都没有得到优化,因为您无法在date_created
上使用索引。如果您确实想要将该列类型更改为日期时间或时间戳,您也可能希望将WHERE条件更改为稍微不那么容易阅读,但更像索引友好的版本如下:
WHERE date_created BETWEEN '2014-12-01 00:00:00' AND '2014-12-31 23:59:29'
答案 1 :(得分:0)
我认为这应该对你有用
SELECT YEARWEEK(date_created), MONTH(date_created), COUNT(*) FROM tickets
WHERE date_created BETWEEN UNIX_TIMESTAMP('$from') AND UNIX_TIMESTAMP('$to') AND
assigned_tech_uid='$uid'
GROUP BY YEARWEEK(date_created), MONTH(date_created)