我想弄清楚为什么我的查询需要这么长时间。每个查询通常需要大约 60 - 90 秒,并且会执行多次。
旧查询:
"select * from $table where type = '".$type."' and transdate >= '".$begdate."' and
transdate<='".$enddate."' and customerin (select customer from master
where targetaccount='Y') ";
新查询:
$q = "SELECT * FROM activity INNER JOIN custactivities ON
activity.activityID = custactivities.activityID WHERE type = '$type' AND
transdate BETWEEN '$begdate' AND '$enddate' AND custnum IN
(SELECT customer FROM master WHERE targetaccount = 'Y')
GROUP BY custactivities.customer";
原始查询大约需要 0.15 秒,新查询每次大约需要 60-90 秒。
这里面确实有一些 PHP,但查询仍然是个问题。
非常感谢任何建议。
最佳答案
在以下列添加索引,如果你没有的话
activityID on both table
type - if it's numeric, don't use the '
transdate
targetaccount - if you can, use numeric, or enum definition for that column for better indexing
如果你的主表不是太大,where targetaccount = 'Y',你可以将它分离到另一个查询,使用 php 获取并使用 implode 将数组插入到你的查询中,而不是使用子查询。
永远不要像 ChrisS 提到的那样使用 * 。
这里是一些 php 和 mysql 的代码片段
$cust = array();
$sql = 'SELECT customer FROM master WHERE targetaccount = "Y"';
$query = mysql_query();
if ($query) {
while ($row = mysql_fetch_row($query)) {
$cust[] = $row[0]
}
}
$sql = "select * from $table where type = '".$type."' and transdate >= '".$begdate."' and
transdate<='".$enddate."'" . (count($cust) ? ' AND custnum IN ('.implode(', ', $cust).')' : '');
我还没有测试过,但我想现在你明白了。
关于php - MySQL新加入的查询与子查询花费的时间太长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26412818/