简体   繁体   English

针对不同日期运行 SQL 查询的最佳方式

[英]Best way to run a SQL query for different dates

I have a PHP application that records the sessions of various devices connected to a server.我有一个 PHP 应用程序,它记录连接到服务器的各种设备的会话。 The database has a table session , with the columns device_id , start_date , end_date .数据库有一个表session ,其中包含列device_idstart_dateend_date To know the number of devices connected on a given date, I can use the request:要知道在给定日期连接的设备数量,我可以使用请求:

SELECT COUNT(DISTINCT device_id)
FROM session
WHERE :date >= start_date AND (:date <= end_date OR end_date IS NULL)

where :date is passed as a parameter to the prepared statement.其中:date作为参数传递给准备好的语句。

This works fine, but if I want to know the number of devices for every days of the year, that makes 365 queries to run, and I'm afraid things could get very slow.这工作正常,但如果我想知道一年中每一天的设备数量,则需要运行 365 个查询,而且我担心事情会变得非常缓慢。 It doesn't feel right to be iterating on the date in PHP, it seems to me that there should be a more optimal way to do this, with a single query to the database.在 PHP 中的日期进行迭代感觉不对,在我看来应该有一种更优化的方法来执行此操作,只需对数据库进行一次查询。

  1. Is it possible do this with a single query?是否可以通过单个查询执行此操作?

  2. Would it actually be faster than to iterate on the date in PHP an running multiple queries?它实际上会比在 PHP 运行多个查询中迭代日期更快吗?


EDIT to answer the comments:编辑以回答评论:

  • I do want the number for each separate day (to draw a graph for example), not just the sum我确实想要每一天的数字(例如绘制图表),而不仅仅是总和

  • the datatype is DATE数据类型是 DATE

If I understand correctly then you first need a table of dates, something like:如果我理解正确,那么您首先需要一个日期表,例如:

create table dates(dt date);
insert into dates(dt) values
('2001-01-01'),
('2001-01-02'),
...
('2100-12-31')

And use a query like so:并使用这样的查询:

select dates.dt, count(session.device_id)
from dates
join session on start_date <= dates.dt and (dates.dt <= end_date or end_date is null)
-- change to left join to include zero counts
where dates.dt >= :date1 and dates.dt <= :date2
group by dates.dt

PS: since you mentioned charts I might add that it is possible to avoid the table of dates. PS:既然你提到了图表,我可能会补充说,可以避免使用日期表。 However, the result will only contain dates on which the count of devices changed.但是,结果将仅包含设备数量发生变化的日期。 Chart APIs usually accept this kind of data but still create data points for all dates in between.图表 API 通常接受此类数据,但仍会为介于两者之间的所有日期创建数据点。

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

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