[英]MySQL query with specific timezone
I have a database storing data for my Laravel/PHP application.我有一个为我的 Laravel/PHP 应用程序存储数据的数据库。 All data is stored in the database as UTC.
所有数据都以 UTC 格式存储在数据库中。
I'm writing a query to get data grouped by date and hour so I can plot the data on a graph.我正在编写一个查询来获取按日期和小时分组的数据,以便我可以 plot 图表上的数据。
Our UI shows reporting data in the America/Los_Angeles
timezone.我们的 UI 显示
America/Los_Angeles
时区的报告数据。
What I'm looking to do is get the last three days data but queried based on the reporting timezone of America/Los_Angeles
.我要做的是获取最近三天的数据,但根据
America/Los_Angeles
的报告时区进行查询。
To get the BETWEEN
dates I'm using the below要获得
BETWEEN
日期,我使用以下
$from = now()
->startOfDay()
->subDays(3)
->timezone('America/Los_Angeles');
$to = now()
->endOfDay()
->timezone('America/Los_Angeles');
This works OK.这工作正常。 So the next step is grouping the data but not grouping it on the column data as that would be
UTC
.因此,下一步是将数据分组,但不将其分组到列 data 上,因为那将是
UTC
。 I would like to group is on the Los_Angeles
timezone.我想组在
Los_Angeles
时区。 So I'm doing the below.所以我正在做下面的事情。
SELECT
DATE(CONVERT_TZ(created_at, '+00:00', '-07:00')) AS grouped_date,
HOUR(CONVERT_TZ(created_at, '+00:00', '-07:00')) AS grouped_hour,
count(*) AS requests
FROM
`advert_requests`
WHERE
created_at BETWEEN '2022-09-09 17:00:00' AND '2022-09-13 16:59:59'
GROUP BY
grouped_date,
grouped_hour
The random issue I'm having is that the grouped data is starting on 2022-09-09
at 10:00
and I'm not sure why.我遇到的随机问题是分组数据从
2022-09-09
年 9 月 9 日10:00
开始,我不知道为什么。
Starting the BETWEEN
at 2022-09-09 17:00:00 America/Los_Angeles
is 2022-09-10 00:00:00 UTC
so when doing the CONVERT_TZ
on the created_at
shouldn't the grouped data start at 0
?在
2022-09-09 17:00:00 America/Los_Angeles
开始BETWEEN
是2022-09-10 00:00:00 UTC
所以在created_at
上执行CONVERT_TZ
时,分组数据不应该从0
开始吗?
Any ideas?有任何想法吗?
Surely this isn't as easy as just setting the timezone to the reporting timezone for the sessions where I run the reporting SELECT
query.当然,这并不像在我运行报告
SELECT
查询的会话中将时区设置为报告时区那样简单。
So I can leave everything else as UTC
.所以我可以将其他所有内容保留为
UTC
。 My application is UTC
and handles timezone conversion in the php/application.我的应用程序是
UTC
并在 php/application.xml 中处理时区转换。 My database is set to UTC
.我的数据库设置为
UTC
。 My MySQL INSERT
's etc are all UTC
.我的 MySQL
INSERT
等都是UTC
。 Then when I want to query anything to be displayed in our UI using our fixed reporting timezone of America/Los_Angeles
I can just set it before running the SELECT
query?然后,当我想使用我们的固定报告时区
America/Los_Angeles
查询要在 UI 中显示的任何内容时,我可以在运行SELECT
查询之前设置它吗?
SET time_zone = '-07:00';
// In the Laravel framework
// DB::update('SET time_zone = ?', ['-07:00']);
And then接着
SELECT
DATE(created_at) AS grouped_date,
HOUR(created_at) AS grouped_hour,
count(*) AS requests
FROM
`advert_requests`
WHERE
created_at BETWEEN '2022-09-10 00:00:00'
AND '2022-09-13 23:59:59'
GROUP BY
grouped_date,
grouped_hour
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.