tags:

views:

165

answers:

2

I want to do this:

Check the top 10 values of points.

Here is my condition:

  • If there are less than 10 records (rows) found, e.g give bonus

  • If the points is in top ten (among hundreds records/rows), give bonus.

So, what i do is (wrong method):

SELECT points FROM `scores` WHERE id = '1' ORDER BY score DESC LIMIT 9 , 1

That will only work if i have more then 9 (at least 10) data/records.

Is there any other way?

I am thinking of using this(not very good though):

 SELECT points FROM `scores` WHERE id = '1' ORDER BY score DESC LIMIT 0 , 10

Then get the last value of mysql_fetch_assoc data. Thus, how do I get the last value of mysql_fetch_assoc data?

A: 

try to use this:

SELECT points FROM (SELECT points FROM scores WHERE id = '1' ORDER BY score DESC LIMIT 10) ORDER BY score LIMIT 1

alemjerus
well, it does not work :(
mysqllearner
A: 

The previous query is close to what you want:

SELECT points FROM (
  SELECT points, score 
  FROM scores 
  WHERE id = '1' 
  ORDER BY score DESC 
  LIMIT 10
) AS top_ten 
ORDER BY score ASC 
LIMIT 1

If you want to stick with mysql_fetch_assoc getting the last value you can utilize mysql_data_seek.

Something like this:

<?php
// ... $result is the result set from your query

$result_count = mysql_num_rows($result);
if ($result_count > 0)
{
    mysql_data_seek($result, $result_count - 1);
}

$row = mysql_fetch_assoc($result);
?>
Mike Lively