Mysql Sub Select Query Optimization
Posted
by Matt
on Stack Overflow
See other posts from Stack Overflow
or by Matt
Published on 2010-01-18T16:24:09Z
Indexed on
2010/03/17
22:01 UTC
Read the original article
Hit count: 538
I'm running a query daily to compile stats - but it seems really inefficient. This is the Query:
SELECT a.id, tstamp, label_id, (SELECT author_id FROM b WHERE b.tid = a.id ORDER BY b.tstamp DESC LIMIT 1) AS author_id
FROM a, b
WHERE (status = '2' OR status = '3')
AND category != 6
AND a.id = b.tid
AND (b.type = 'C' OR b.type = 'R')
AND a.tstamp1 BETWEEN {$timestamp_start} AND {$timestamp_end}
ORDER BY b.tstamp DESC
LIMIT 500
This query seems to run really slow. Apologies for the crap naming - I've been asked to not reveal the actual table names.
The reason there is a sub select is because the outer select gets one row from the table a and it gets a row from table b. But also need to know the latest author_id from table b as well, so I run a subselect to return that one. I don't want to run another select inside a php loop - as that is also inefficient.
It works correctly - I just need to find a much faster way of getting this data set.
© Stack Overflow or respective owner