我有一个 sql 查询具有数百万条记录的 MySql 表。这将在大约 2 秒内在 phpMyAdmin 中执行,但是当从 PHP 脚本运行时,它不会完成执行。
select
concat(p1.`Date`," ",p1.`Time`) as har_date_from,
concat(p2.`Date`," ",p2.`Time`) as har_date_to,
(select concat(p3.`Date`," ",p3.`Time`) from
power_logger p3
where p3.slno between 1851219 and 2042099
and p3.meter_id="logger1"
and str_to_date(concat(p3.`Date`," ",p3.`Time`),"%d/%m/%Y %H:%i:%s") >=
str_to_date(concat(p1.`Date`," ",p1.`Time`),"%d/%m/%Y %H:%i:%s")
order by p3.slno limit 1) as cur_date_from,
(select concat(p4.`Date`," ",p4.`Time`) from
power_logger p4
where p4.slno between 1851219
and 2042099
and p4.meter_id="logger1"
and str_to_date(concat(p4.`Date`," ",p4.`Time`),"%d/%m/%Y %H:%i:%s") >=
str_to_date(concat(p2.`Date`," ",p2.`Time`),"%d/%m/%Y %H:%i:%s")
order by p4.slno
limit 1
)
as cur_date_to,
p1.THD_A_N_Avg-p2.THD_A_N_Avg as thd_diff
from power_logger p1
join
power_logger p2
on p2.slno=p1.slno+1
and p1.meter_id="fluke1"
and p2.meter_id=p1.meter_id
and p1.slno between 2058609 and 2062310
and p1.THD_A_N_Avg-p2.THD_A_N_Avg>=2.0000
php脚本:
$query=/*The query above passed as string*/
$mysql=mysql_connect('localhost','username','pwd') or die(mysql_error());
mysql_select_db('dbname',$mysql);
$rows=mysql_query($query,$mysql) or die(mysql_error());
mysql 连接和相关内容没有问题,因为我成功运行了许多其他查询。我已经在meter_id 和 Date,Time 上设置了索引。slno 是自动增量值。我知道有人问过类似的问题,因为我从研究中发现了很多,但没有一个对我有真正的帮助。如果有人可以帮助我找到解决方案,请提前感谢。
查询说明:查询包含数百万条记录的power_logger表,表中列有THD_A_N_AVG、meter_id、slno、Date和Time。这会从两个连续行中选择日期和时间,其中 THD_A_N_AVG 之间的差异大于或等于 2。当获取这些日期时,它甚至必须在不同的 slnos 范围内获取日期和时间其中日期和时间最接近之前获取的一次,因此形成 har_date_from、har_date_to、cur_date_from、cur_date_to。这里搞砸的是嵌套选择。