MySQL查询按月返回行数

时间:2014-04-22 23:35:04

标签: php mysql sql mysqli prepared-statement

我正试图在counts number of rowstable 12 months逐月12 counts获得SELECT ( SELECT COUNT(i.id) FROM intrusions i, devices d WHERE i.device_id = d.id AND d.primary_owner_id = '1' AND FROM_UNIXTIME(start_time/1000) like '2014-04%', SELECT COUNT(i.id) FROM intrusions i, devices d WHERE i.device_id = d.id AND d.primary_owner_id = '1' AND FROM_UNIXTIME(start_time/1000) like '2014-03%', SELECT COUNT(i.id) FROM intrusions i, devices d WHERE i.device_id = d.id AND d.primary_owner_id = '1' AND FROM_UNIXTIME(start_time/1000) like '2014-02%', etc ) 1 user

到目前为止,我有这种非常丑陋的方式:

many devices

这些表已设置好,1 device可以many intrusionsprimary_owner_id可以有date,因此需要额外的条件。

将使用PHPprepared statements中动态添加{{1}}和{{1}}。有没有更好的方法来写出来,这不会涉及如此多的重复和绑定24个参数?任何帮助将不胜感激

2 个答案:

答案 0 :(得分:0)

您应该使用分组来实现此目的。就像这样。

SELECT
    CONCAT(YEAR(FROM_UNIXTIME(start_time/1000)), '-', MONTH(FROM_UNIXTIME(start_time/1000))) AS `year_month`,
    COUNT(id) AS `count`
FROM intrusions AS i
INNER JOIN devices AS d
  ON i.device_id = d.id
WHERE d.primary_owner = ?
GROUP BY `year_month`
ORDER BY `year_month` DESC
LIMIT 12

答案 1 :(得分:0)

您可以使用DATE_FORMAT选择年份和月份,并且可以使用DATE_SUB创建WHERE条件,选择上个月的项目。 Haven没有测试过这种语法,但它应该接近正确。

这与最后一个答案一致,但首先使用更简洁的DATE_FORMAT并使用DATE_SUB自动选择过去12个月来改进

SELECT
  DATE_FORMAT(start_date, "%Y-%m") AS `month`,
  COUNT(`id`) AS `count`
FROM intrusions
INNER JOIN devices ON (intrusions.device_id = devices.id)
WHERE
  d.primary_owner_id = 1 AND
  DATE_SUB(CUR_DATE(), INTERVAL 12 MONTH) < start_date
GROUP BY month
ORDER BY month DESC