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 Link to comment https://forums.phpfreaks.com/topic/20774-posttopic-query-problem-stop-query-in-a-loop/ 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. Link to comment https://forums.phpfreaks.com/topic/20774-posttopic-query-problem-stop-query-in-a-loop/#findComment-91973 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 Link to comment https://forums.phpfreaks.com/topic/20774-posttopic-query-problem-stop-query-in-a-loop/#findComment-92006 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] Link to comment https://forums.phpfreaks.com/topic/20774-posttopic-query-problem-stop-query-in-a-loop/#findComment-92065 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. Link to comment https://forums.phpfreaks.com/topic/20774-posttopic-query-problem-stop-query-in-a-loop/#findComment-92341 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.