I’ve looked into Dynamic SQL and the inc() function, but neither are really what I’m after.
Say I have a database like this:
grade name age
9 Bob 9
10 Sue 11
11 Larry 15
9 Joe 8
10 Carrot 10
I want to create a table that first selects all the rows with the lowest grade (9) then displays the oldest. It then goes through and searches for the next highest grade (10) and displays the oldest. Then goes to the next highest grade (11) and displays the oldest.
I’d like for them all to be in the same table and not have to write out a separate SQL call and different PHP variables for each grade.
This is the SQL call I have right now:
$query = "SELECT * FROM horses WHERE grade='1' ORDER BY points DESC LIMIT 1" or die(mysql_error());
Is there a way I can make the grade column increment until it reaches the highest number in the database?
Thanks for any suggestions.
You don’t need a loop for this if I understand your request. Instead, you need a
MAX()aggregate grouped bygrade. The following method should work independently of your RDBMS. It relies on aJOINagainst a subquery which returns the greatestagepergroupto get theage/grouppair and join that back against the main table to retrieve thename(and other columns as needed).Here is an example on SQLFiddle.com
Returns:
It is generally far faster an less resource-intensive to do one query instead of multiple queries in a loop, so this should be the approach whenever possible.