创建表格
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下一行的行(rank)
例如:最后一个id的排名是3!
想要结果
id percent rank
4 40 2
最佳答案
要解决您的问题,我们有2种语言选项:
原文链接:https://www.f2er.com/mysql/433793.html> PHP很容易 – >不好玩.
> MysqL – >你已经使用MysqL完成了部分工作,所以我就这样完成了.
脚步 :
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,15,10
让我们开始有趣(pbm起步 – Kappa):MysqL中没有任何explode()函数.
>在@str_rank中获取与@next_rank相关的百分比
我们用本机功能做的最好的是:
> SELECT SUBSTRING_INDEX(@str_rank,’,@ next_rank);
>结果:50,40
但我们只有’40’
– >让我们找到/创建一个函数来提取1到-1位置之间的字符串(大到Arman P.)
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,pos-1)) + 1),'');
.
SELECT SPLIT_STRING(@str_rank,@ next_rank)到@next_percentage;
这将在@next_percentage中存储’40’
结果:(最后)
SELECT *,@next_rank as rank
FROM goal_implement
WHERE percent = @next_percentage;
输出:
id percent rank
4 40 2
PHP版本:
$Array_test假定您的查询返回的数组
PHP
$array_test = array(array(6,3),array(5,50,1),array(4,2),array(3,array(2,5),array(1,10,6));
$next_rank = $array_test[0][2] - 1;
foreach($array_test as $row)
if($row[2] == $next_rank)
{
print "
输出:
Array
(
[0] => 4
[1] => 40
[2] => 2
)