I am having some issues optimizing a mySQL query that I have been using sub-queries on to try and get the previous and next IDs based off the ID in the query. When I use the EXPLAIN function in mySQL it shows that one of my sub-queries is running through 690k+ rows, which is what I am guessing is affecting the performance.
I have tried to limit the sub-queries to return just just one result and used a MIN and MAX in the sub-queries, but both of those options still returned large sets of rows.
SELECT c.*,
(SELECT id FROM cards WHERE id > '733290' ORDER BY id ASC LIMIT 1) AS 'prev',
(SELECT id FROM cards WHERE id < '733290' ORDER BY id DESC LIMIT 1) AS 'next'
FROM cards c
LEFT JOIN albums a ON (a.id = cs.album_id)
WHERE c.id = '733290'
In the explain this was the results:
id select_type table type possible_keys key key_len ref rows Extra 5 SUBQUERY cards range PRIMARY,user_id PRIMARY 4 NULL 696177 Using where 4 SUBQUERY cards range PRIMARY,user_id PRIMARY 4 NULL 4 Using where
Edit: Here are the definitions for the cards table:
Keyname Type Unique Packed Column Cardinality Collation Null Comment PRIMARY BTREE Yes No id 696183 A No user_id BTREE No No user_id 5438 A No album BTREE No No album 258 A No
cardstable? We need to see this in order to be able to suggest some potential optimizations.