创建表格
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);
查询
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
结果
id percent rank
6 20 3
5 50 1
4 40 2
3 20 3
2 15 5
1 10 6
我不知道如何获取最后一个ID下一个row(rank)
例如:最后一个id的等级是3!
想要结果
id percent rank
4 40 2
答案 0 :(得分:1)
首先,获取最后一个等级的其他ID ...然后为其添加一个。示例如下。
SELECT id FROM YOUR_TABLE WHERE rank = $last_rank AND id != $last_id ORDER BY id DESC;
SELECT * FROM YOUR_TABLE WHERE id = $row['id'] + 1;
答案 1 :(得分:1)
试试这个:
select * from goal_implement where rank=(select (rank-1)
from goal_implement where id=(select max(id) from goal_implement));
希望你能得到输出。
答案 2 :(得分:1)
要解决您的问题,我们有两种语言选择:
Php很容易 - >不好玩。
MYSQL - >你已经使用Mysql完成了部分工作,所以我就这样完成了。
SQLFIDDLE: Demo
步骤:
获取最后一个ID的排名+获取所有百分比的字符串
SELECT FIND_IN_SET( percent, (SELECT GROUP_CONCAT( percent ORDER BY percent DESC )
FROM goal_implement )) - 1 into @next_rank
FROM goal_implement
ORDER BY id DESC
LIMIT 1;
SELECT GROUP_CONCAT( percent ORDER BY percent DESC )
FROM goal_implement into @str_rank;
此代码将为您提供:
@next_rank @str_rank
2 50,40,20,20,15,10
让我们开始有趣(pbm起步 - Kappa): MYSQL中没有任何explode()函数。
@next_rank
@str_rank
相关的百分比
我们用本机功能做的最好的是:
SELECT SUBSTRING_INDEX(@str_rank, ',', @next_rank);
结果:50,40
但我们只{/ 1}}
- >让我们找到/创建一个函数来提取+1和-1之间的字符串(大到Arman P。)
'40'
。
CREATE FUNCTION SPLIT_STRING(str VARCHAR(255), delim VARCHAR(12), pos INT)
RETURNS VARCHAR(255)
RETURN REPLACE(SUBSTRING(SUBSTRING_INDEX(str, delim, pos),
LENGTH(SUBSTRING_INDEX(str, delim, pos-1)) + 1),
delim, '');
这会将SELECT SPLIT_STRING(@str_rank, ',', @next_rank) into @next_percentage;
存储在'40'
结果:(最后)
@next_percentage
输出:
SELECT *, @next_rank as rank
FROM goal_implement
WHERE percent = @next_percentage;
PHP版本:
id percent rank
4 40 2
应该是您的查询返回的数组
$Array_test
输出
<?php
$array_test = array(array(6,20,3), array(5,50,1), array(4,40,2),
array(3,20,3), array(2,15,5), array(1,10,6));
$next_rank = $array_test[0][2] - 1;
foreach($array_test as $row)
if($row[2] == $next_rank)
{
print "<pre>";
print_r($row);
print "</pre>";
}
?>