Table1仅为1mb,table2为10mb,但查询至少需要30秒才能加载。是因为SUM和COUNT函数吗?
$index = mysql_query("CREATE index table1_timestamp on table1(timestamp)");
$result = mysql_query("SELECT
table1.user_id,
table1.timestamp,
COUNT(DISTINCT table1.call_id) as calls,
SUM(table2.recording_file_duration) / 60 as minutes
FROM
table1
JOIN table2 ON
table1.call_id = table2.id
WHERE
table1.user_id = '244'
AND
table1.timestamp >= '2013-07-01' and table1.timestamp < '2013-08-01'
GROUP BY
table1.user_id,
DAY(table1.timestamp)
ORDER BY
table1.timestamp DESC");
编辑:我刚检查过,表2有300,000行。这是为什么?
答案 0 :(得分:1)
添加WHERE
子句可用于table1
的索引。另外,添加JOIN
可用于table2
的索引。
添加以下索引:
table1(user_id, timestamp) // Order is important here, ranges go last
table2(id)
当然,如果table2.id
是您的主键,则无需添加该索引。
为了进一步改善结果,您可以添加覆盖索引:
table1(user_id, timestamp, call_id)
table2(id, recording_file_duration)
如果您使用InnoDB并且其中任何列都是主键,请从索引中删除它们。