I am writing a query for a database with 2 large tables. It takes forever to get the results. I have limited the results to a specific year although ideally I want to get them all at once. The sql is:
$sql ="SELECT month(table1.started) as month, count( table1.id ) AS count
FROM table1
INNER JOIN table2 ON table1.`sessionId`=table2.`sessionId`
WHERE table2.item_id=".$id." AND YEAR(table1.started) = '".$year."'
GROUP BY MONTH(started)
ORDER BY MONTH(table1.started) ASC";
php:
$result = $mysqli->query($sql, MYSQLI_USE_RESULT); //unbuffered does not speed it up
if ($result) {
while($info = $result->fetch_assoc()) {$output.="....";}
There are about 145k rows in table1 (of which about 25k from the year in the query) and 250k in table2. While fetching these results the website is inaccessible. It takes about 10 seconds to get a resultset of only 340 items, to get one of a couple of thousand results takes more than 2 minutes. Querying results from table1 only is very fast, even for the complete table grouped by year and month. Is there a way to speed things up?