I have Table1 and Table2 related on Table1.ID. There can be zero or more Table2 records for a given Table1.ID. I have a view where I want to get Table2.Value where Table2.ID is max for a given Table1.ID. A friend suggested a derived table, but that requires a subquery in the from clause, and MySQL doesn't like that. Are there any other ways to do this? I tried setting up a secondary view to take the place of the subquery, but it seems very slow. I also tried using a having clause to test Table2.ID = MAX(Table2.ID), but it doesn't recognize the column unless I put it into the group by, which screws everything else up.
A:
SELECT t1.*, t2a.*
FROM Table1 t1
LEFT JOIN Table2 t2a
ON (t1.table1_id = t2a.table1_id)
LEFT JOIN Table2 t2b
ON (t1.table1_id = t2b.table1_id AND t2a.table2_id < t2b.table2_id)
WHERE t2b.table2_id IS NULL
AND t1.table1_id = ?;
Bill Karwin
2009-09-03 23:13:41
Works great! Much quicker than the secondary view. Thanks. Any performance concerns I should look out for with this method? With regard to table sizes or indexing or anything?
Brian
2009-09-04 14:44:28
Well, you should always analyze with EXPLAIN any query you need to have good performance, and try to make sure it's using indexes well and not doing filesort/temporary table. But this query is about as scalable as you can get in a normalized database.
Bill Karwin
2009-09-04 15:18:25
Sounds great. Thanks again for the help.
Brian
2009-09-04 16:16:08