m11oct Posted September 14, 2006 Share Posted September 14, 2006 I have TABLE1 with column A where A is a unique index. (Say topics on a forum, for example.)I have TABLE2 with columns B, C and D where B is the unique index and C will refer to one of the rows in TABLE1. (Say posts on a forum, where C identifies to which topic the post belongs and D is the time of the post.)I would like be able to...For each row (value of A) in TABLE1, identify the row (value of B) in TABLE2 where C=A and D is greatest (i.e. greater than any other value of D where C=A).I am currently using the following code but it is very slow:$res=query("SELECT a FROM table1");while ($row=mysql_fetch_row($res)) { $res2=query("SELECT b,c,d FROM table2 WHERE c=".$row[0]." ORDER BY d DESC"); //the above will return one result which will be $result echo $row[0] . ';' . $result;}I would like to be able to just have one query and run through the loop without having to do another query in the loop.Thank you Quote Link to comment Share on other sites More sharing options...
fenway Posted September 14, 2006 Share Posted September 14, 2006 Sounds like you need a correlated subquery, where the inner query finds the group-wise maximum, and then the outer query simply goes through all the rows. Quote Link to comment Share on other sites More sharing options...
m11oct Posted September 14, 2006 Author Share Posted September 14, 2006 Can you tell me what the query I would need would look like?Thanks Quote Link to comment Share on other sites More sharing options...
shoz Posted September 14, 2006 Share Posted September 14, 2006 This should be what you're looking for.[code]SELECTt1.a, t2.b, t2.c, t2.dFROMtable1 AS t1INNER JOINtable2 AS t2ON t1.a = t2.cINNER JOIN( SELECT c, MAX(d) AS d FROM table2 GROUP BY c) AS t2maxONt2.c = t2max.cANDt2.d = t2max.d[/code] Quote Link to comment Share on other sites More sharing options...
fenway Posted September 15, 2006 Share Posted September 15, 2006 Or you could use a derived table, which is much better as far as performance is concerned, as shoz pointed out. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.