Due to a need to join multiple tables in a single query, I am not able to use SQL_CALC_FOUND_ROWS (or LIMIT) on the outer query (the number would be higher than expected).
Here is the ideal query, if MySQL supported using SQL_CALC_FOUND_ROWS within subqueries:
SELECT events.*, bands.*
FROM events
LEFT JOIN bands ON events.event_id = bands.event_id
WHERE e.event_id IN (
SELECT * FROM (
SELECT SQL_CALC_FOUND_ROWS e.event_id
FROM events
WHERE events.date > NOW()
ORDER BY events.date ASC LIMIT 0, 25
) ALIAS
)
ORDER BY events.date ASC
This question suggests creating an aliased table, but I am not sure if I can do this with PDO prepared statements.
I attempted this, but got a parse error because FOUND_EVENTS was interpreted as being a (nonexistent) column name:
$st1 = $pdo->prepare("(SELECT SQL_CALC_FOUND_ROWS e.event_id
FROM events
WHERE events.date > NOW()
ORDER BY events.date ASC LIMIT 0, 25
) AS FOUND_EVENTS");
$st2 = $pdo->prepare("SELECT events.*, bands.*
FROM events
LEFT JOIN bands ON events.event_id = bands.event_id
WHERE e.event_id IN (
FOUND_EVENTS
)
ORDER BY events.date ASC");
$st1->execute();
$st2->execute();
I would prefer to stick to prepared statements if possible, but any working solution would be great!
I’d do it in two separate queries.
If your reason for using SQL_CALC_FOUND_ROWS is to try and save execution time, you may be surprised to know that in many cases, it will be much, much faster, and less load on the database, to use two separate queries instead, one of them with a simple COUNT(*) grouping function to calculate the total rows, and the other one with the LIMIT in place to actually retrieve the rows.
Here is more explanation of why this is the case.
What’s more, if you do it in two separate queries, then you can do the one that actually fetches the rows first and then you only need to do the second one with the COUNT(*) if the first one returned the maximum number of rows.