简体   繁体   English

MySQL查询按月返回行数

[英]MySQL query to return counts of rows by month

I'm trying to get counts of the number of rows in a table for the last 12 months , on a month by month basis to give 12 counts . 我试图让counts的的number of rowstable的最后12 months每月基础上,每月给12 counts

So far, I have this really ugly way of doing it: 到目前为止,我的处理方式非常丑陋:

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
)  

The tables are set up so 1 user can have many devices and 1 device can have many intrusions , hence the extra conditions. 设置这些表是为了使1 user可以拥有many devices1 device可以拥有many intrusions ,因此会产生额外的条件。

The primary_owner_id and the date will be added in dynamically in PHP using prepared statements . 将使用prepared statementsPHP中动态添加primary_owner_iddate Is there a better way to write this out which wouldn't involve so much repitition and binding 24 parameters? 有没有一种更好的方法可以写出来,而不会涉及太多的重新分配和绑定24个参数? Any help would be appreciated 任何帮助,将不胜感激

You should use grouping to get this. 您应该使用分组来做到这一点。 So something like this. 像这样

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

You can use DATE_FORMAT to select the Year and Month, and you can use DATE_SUB to create a WHERE condition selecting items in the last month. 您可以使用DATE_FORMAT选择年份和月份,也可以使用DATE_SUB创建WHERE条件,选择上个月的项目。 Haven't tested this syntax but it should be close to correct. 尚未测试此语法,但应该正确无误。

This is along the same lines as the last answer but improves by firstly using the more succinct DATE_FORMAT and using DATE_SUB to automatically select the last 12 months 这与上一个答案相同,但首先使用更简洁的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

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

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