Forum Moderators: coopster
I need to select the last 20 records form a table, and with those 20 records I need to take the 10 with the lowest value and add them together to come out wiht a single number. My table only has 2 columns: ID and Number.
I can easily get the 20 lowest using:
$query_rsLimited = "SELECT * FROM test ORDER BY testID DESC LIMIT 20";
$rsLimited = mysql_query($query_rsLimited, $ConnClub) or die(mysql_error());
$row_rsLimited = mysql_fetch_assoc($rsLimited);
$totalRows_rsLimited = mysql_num_rows($rsLimited);
My question is how best to get the 10 highest 'Number' values out of the 20 records and sum them.
Help?!
2. sort($array)
[php.net...]
3. loop through first 10 adding amounts
$newarray = array();
$query_rsLimited = "SELECT id, value FROM test ORDER BY testID DESC LIMIT 20";
$rsLimited = mysql_query($query_rsLimited, $ConnClub) or die(mysql_error());
while($row=mysql_fetch_assoc($rsLimited)) {array_push($newarray, $row);}
$query_rsLimited = "SELECT * FROM test ORDER BY testID DESC LIMIT 20";
$row_rsLimited = mysql_fetch_assoc($rsLimited);
while($row_rsLimited=mysql_fetch_assoc($rsLimited))
{
$newarray[]=$row_rsLimited['testNum'];
}
sort($newarray);
array_splice($newarray, 10);
$total = array_sum($newarray);
echo $total;
Works great!
Cheers.
$row_rsLimited = mysql_fetch_assoc($rsLimited); #remove this!
It is advancing the internal pointer before the while loop, hence missing the first result ;)
When using the LIMIT keyword with only one argument, the argument constrains the number of rows returned, in this case 20. If you use two arguments, then the first argument is the offset of the initial row, which is indeed 0 (not 1), but the second argument still specifies the maximum number of rows to return. You don't need to specify both arguments but if you were to use both in this case, you would specify
LIMIT 0, 20in your SELECT [dev.mysql.com] statement.