如何在 PHP MySQL 的单个查询中获取相隔 10 分钟的所有行?
How fetch all rows which are 10 min apart in single query in PHP MySQL?
我有 table device 其中包含记录的温度值及其测量时间。我需要通过仅获取至少 10 分钟的值来对该数据进行采样分开.(
例如,如果第一行读取 (30k,8.40.00),那么下一行包含 8.50.00 之后或 8.50.00 之后的值(以接下来的 10 分钟值为准)。
我的时间列存储为字符串格式 (H.m.s)。
我当前在 PHP 中的 select 查询是
$sql="select value ,time from device where time >= '$interval' order by time limit 1";
使用strtotime方法,$interval值增加10分钟。每次select只有一行
问题是我需要使用循环来获取所有可能的行。我的问题是如何在不使用循环的情况下获取所有行,就像在单个查询中一样?为了使用 for 循环,我需要提前知道行数。
我认为可行:
$sql="select `value`,`time` from `device` where MINUTE(`time`) IN (0, 10, 20, 30, 40, 50) order by `time`";
如果您有多个按 10 分钟计算的值并且只想要一个,请使用按分钟分组(time
)
这比你想象的要复杂。您不能只查看连续行之间的间隔,您需要跟踪选择的最后一行以标识下一行。这意味着一个迭代过程;在 SQL 中,这通常使用递归查询实现 - MySQL 仅支持起始版本 8.0。
考虑:
with recursive cte as (
select value, time
from device
where time = (select min(time) from device)
union all
select d.value, d.time
from cte c
inner join device d on d.time = (
select min(d1.time) from device d1 where d1.time >= c.time + interval 10 minute
)
)
select * from cte
我建议首先使用 window 函数获取 10 分钟后(至少)每一行的值,然后应用递归子查询:
with recursive d(value, time, next_time) as (
select value, time,
min(time) over (order by time
range between interval 10 minute following and unbounded following
) as next_time
from device
)
recursive cte(value, time, next_time) as (
(select value, time, next_time
from d
order by time
limit 1
) union all
select d.value, d.time, d.next_time
from cte join
d
on device.time = cte.next_time
)
select *
from cte;
Here 是一个 db<>fiddle.
我有 table device 其中包含记录的温度值及其测量时间。我需要通过仅获取至少 10 分钟的值来对该数据进行采样分开.( 例如,如果第一行读取 (30k,8.40.00),那么下一行包含 8.50.00 之后或 8.50.00 之后的值(以接下来的 10 分钟值为准)。 我的时间列存储为字符串格式 (H.m.s)。 我当前在 PHP 中的 select 查询是
$sql="select value ,time from device where time >= '$interval' order by time limit 1";
使用strtotime方法,$interval值增加10分钟。每次select只有一行
问题是我需要使用循环来获取所有可能的行。我的问题是如何在不使用循环的情况下获取所有行,就像在单个查询中一样?为了使用 for 循环,我需要提前知道行数。
我认为可行:
$sql="select `value`,`time` from `device` where MINUTE(`time`) IN (0, 10, 20, 30, 40, 50) order by `time`";
如果您有多个按 10 分钟计算的值并且只想要一个,请使用按分钟分组(time
)
这比你想象的要复杂。您不能只查看连续行之间的间隔,您需要跟踪选择的最后一行以标识下一行。这意味着一个迭代过程;在 SQL 中,这通常使用递归查询实现 - MySQL 仅支持起始版本 8.0。
考虑:
with recursive cte as (
select value, time
from device
where time = (select min(time) from device)
union all
select d.value, d.time
from cte c
inner join device d on d.time = (
select min(d1.time) from device d1 where d1.time >= c.time + interval 10 minute
)
)
select * from cte
我建议首先使用 window 函数获取 10 分钟后(至少)每一行的值,然后应用递归子查询:
with recursive d(value, time, next_time) as (
select value, time,
min(time) over (order by time
range between interval 10 minute following and unbounded following
) as next_time
from device
)
recursive cte(value, time, next_time) as (
(select value, time, next_time
from d
order by time
limit 1
) union all
select d.value, d.time, d.next_time
from cte join
d
on device.time = cte.next_time
)
select *
from cte;
Here 是一个 db<>fiddle.