我有一个循环遍历 2000+ 条记录的 PHP 脚本,它使用了一个 while 循环。在这个while循环中,必须执行postgres sql查询,不幸的是它不能从while循环中排除。
$sql = "(SELECT (timestamp) AS time FROM followups as f
JOIN campaigns as c ON c.id = f.campid
WHERE c.clientid = ".trim($clientid)." AND c.contractno = '".trim($c)."' AND (LOWER(person) IN (SELECT LOWER(userid) FROM users WHERE type IN('S','X')) OR LOWER(person) IN (SELECT LOWER(name) FROM users WHERE type IN('S','X'))) )
UNION ALL (SELECT (timestamp) AS time FROM followups as f WHERE (contractno ='".trim($c)."'
OR contractno LIKE '%".trim($c)."||".trim($clientid)."%'
OR contractno = '".trim($c)."||".trim($clientid)."') AND (LOWER(person) IN (SELECT LOWER(userid) FROM users WHERE type IN('S','X')) OR LOWER(person) IN (SELECT LOWER(name) FROM users WHERE type IN('S','X'))) )
UNION ALL (select (f.timestamp) AS time FROM followups as f
JOIN campaigns as c on c.id = f.campid WHERE c.clientid = ".trim($clientid)."
AND c.clientid in (
SELECT id FROM easy_mapping where id = ".trim($clientid).") AND (LOWER(person) IN (SELECT LOWER(userid)
FROM users WHERE type IN('S','X')) OR LOWER(person) IN
(SELECT LOWER(name) FROM users WHERE type IN('S','X'))))";
$result = pg_query($conn,$sql);
上面的查询包含在 while 循环中,前几条记录执行得非常快,然后脚本开始变慢,完成脚本需要将近一天的时间。有没有办法以不同的方式编写上面的确切查询以获得相同的结果?
更新:
这是完整的循环
$dates = array();
$clientid = str_replace("\t", '', $clientid);
foreach ($contracts as $c) {
$c = str_replace("\t", '', $c);
$sql = "(SELECT MAX(timestamp) AS time FROM followups as f
JOIN campaigns as c ON c.id = f.campid
WHERE c.clientid = ".trim($clientid)." AND c.contractno = '".trim($c)."' AND (LOWER(person) IN (SELECT LOWER(userid) FROM users WHERE type IN('S','X')) OR LOWER(person) IN (SELECT LOWER(name) FROM users WHERE type IN('S','X'))) )
UNION ALL (SELECT MAX(timestamp) AS time FROM followups as f WHERE (contractno ='".trim($c)."'
OR contractno LIKE '%".trim($c)."||".trim($clientid)."%'
OR contractno = '".trim($c)."||".trim($clientid)."') AND (LOWER(person) IN (SELECT LOWER(userid) FROM users WHERE type IN('S','X')) OR LOWER(person) IN (SELECT LOWER(name) FROM users WHERE type IN('S','X'))) )
UNION ALL (select MAX(f.timestamp) AS time FROM followups as f
JOIN campaigns as c on c.id = f.campid WHERE c.clientid = ".trim($clientid)."
AND c.clientid in ( SELECT id FROM easy_mapping where id = ".trim($clientid).") AND (LOWER(person) IN (SELECT LOWER(userid) FROM users WHERE type IN('S','X')) OR LOWER(person) IN (SELECT LOWER(name) FROM users WHERE type IN('S','X'))))";
$result = pg_query($conn,$sql);
if (pg_num_rows($result)>0) {
while ($row = pg_fetch_array($result, null, PGSQL_ASSOC)) {
if (empty($row['time'])) {
continue;
}
$dates[] = $row['time'];
}
}
pg_free_result($result);
}
if (empty($dates)) {
return false;
} else {
$max = max($dates);
if (strtotime(date("Y-m-d")) < strtotime(date("Y-m-t"))) {
$compdate = date("Y-m-01", strtotime("-1 month") );
} else {
$compdate = date("Y-m-01");
}
if (strtotime($compdate) > $max) {
return false;
} else {
return true;
}
}
unset($dates);