gpt4 book ai didi

php - MySQL 查询按月返回行数

转载 作者:行者123 更新时间:2023-11-30 00:21:05 26 4
gpt4 key购买 nike

我正在尝试获取counts number of rows的在 table最后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 devices1 device可以有many intrusions ,因此有额外的条件。

primary_owner_iddate将动态添加在PHP中使用prepared statements 。有没有更好的方法来写出来,而不需要太多的重复和绑定(bind) 24 个参数?任何帮助将不胜感激

最佳答案

您应该使用分组来获得此结果。所以像这样。

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

关于php - MySQL 查询按月返回行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23232167/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com