将等级中的下一行取到“最后一个ID的等级”?

时间:2015-06-09 03:13:37

标签: php

需要帮助!

Mysql查询:

CREATE TABLE goal_implement( id INT, percent INT ); 

INSERT INTO goal_implement VALUES 
  (1,10),
  (2,15),
  (3,20),
  (4,40),
  (5,50),
  (6,20);

我的PHP代码 - 此代码显示下面的结果表....

<?php
$query2 = "SELECT _id, percent, FIND_IN_SET( percent, (
SELECT GROUP_CONCAT( percent
ORDER BY percent DESC ) 
FROM goal_implement )
) AS rank
FROM goal_implement 
ORDER BY id DESC 
";

我希望这个块成为评论的焦点:我需要php代码;不是mysql查询...

$result2 = mysql_query($query2, $connection);
if($result2 === FALSE) {
    die(mysql_error());
}
while($row = mysql_fetch_array($result2))
{
echo
"<tr>
<td>{$row['id']}</td>
<td>{$row['percent']}</td>
<td> {$row['rank']} </td>    
</tr>\n";       
} 
?>

结果:

id  percent rank
6   20      3
5   50      1
4   40      2
3   20      3
2   15      5
1   10      6

我不知道如何获取最后一个id上的下一行(等级),例如:last id&#39; s rank是3!我希望结果低于......

使用PHP获得的结果:

4   40      2

3 个答案:

答案 0 :(得分:0)

由于您使用的是mysql_fetch_array(),为什么不使用它的索引?

$row['rank'][$incrementHere]

答案 1 :(得分:0)

试试这个:

<?php

$result2 = mysql_query($query2, $connection);
if($result2 === FALSE) {
    die(mysql_error());
}

// store rows by rank
// also get the last_id_rank from the first row
$by_ranks = array();
$last_id_rank = FALSE;
while($row = mysql_fetch_array($result2)) {
    $by_ranks[$row['rank']][] = $row;
    if ($last_id_rank === FALSE) {
        $last_id_rank = $row['rank'];
    }
}

// get the results
$get_results = function($by_ranks, $last_id_rank) {

    // get a sorted array of that's smaller than $last_id_rank
    $ranks = array_filter(array_keys($by_ranks), function($var) use($last_id_rank) {
        return $var < $last_id_rank;
    });
    rsort($ranks); // sort ranks by descending order

    // get the rank that is just smaller than $last_id_rank
    if (sizeof($ranks) == 0) {
        return array();
    } else {
        return $by_ranks[$ranks[0]];
    }

};
$results = $get_results($by_ranks, $last_id_rank);

// display results
foreach ($results as $row) {
    echo "<tr>
        <td>{$row['id']}</td>
        <td>{$row['percent']}</td>
        <td> {$row['rank']} </td>    
        </tr>\n";
}
?>

答案 2 :(得分:0)

我可以使用HAVING子句

过滤数据
$query="SELECT id, percent, FIND_IN_SET( percent, (

SELECT GROUP_CONCAT( percent
ORDER BY percent DESC )
FROM goal_implement )
) AS rank
FROM goal_implement
HAVING id >".$last_id_rank."
ORDER BY id ASC limit 1";