mysql 对表进行排序并获取行位置

发布于 2024-10-06 14:07:06 字数 236 浏览 1 评论 0原文

我在 mysql 中遇到了问题,我有一个 ID 和 nubmer 表...类似的东西

ID -------- number
3  -------- 340
1  -------- 10
12 -------- 23

现在我想通过 ID 进行选择,假设 ID=3,有没有一种方法可以说明 的位置是什么排序表中的这一行?在这种情况下,ID = 3 将具有第一个位置,因为数字值最高。 ID=12 将有第二个位置...等等。

I've got a problem in mysql, I have a table of ID and nubmer ... somthing like that

ID -------- number
3  -------- 340
1  -------- 10
12 -------- 23

And now I would like to selecet by ID, let's say ID=3 and is there a way of saying what is the position of this row in sorted table? In this case, ID = 3 would have first position, cuase of highest value in number. ID=12 would have second position ... and so on.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

給妳壹絲溫柔 2024-10-13 14:07:06
set @row_number:=0;
select * from 
  (select ID, @row_number:=@row_number+1 from your_table order by number desc) 
   as row_to_return 
where ID=3;

可以更改上述查询,将 ID 替换为您需要的任何内容。
然而,对于简单的使用,ORDER BY number DESC 更好并且经过优化。

set @row_number:=0;
select * from 
  (select ID, @row_number:=@row_number+1 from your_table order by number desc) 
   as row_to_return 
where ID=3;

The above query can be change to replace ID to anything you need.
However, for simple usage, ORDER BY number DESC is better and optimized.

永不分离 2024-10-13 14:07:06

如果有用的话尝试这个查询。

SELECT ID,number FROM table_name ORDER BY number DESC;

谢谢。

try this query if usefull.

SELECT ID,number FROM table_name ORDER BY number DESC;

Thanks.

鱼忆七猫命九 2024-10-13 14:07:06

如果您通过 PHP 返回结果集,则可以使用 PHP 来确定 ID 字段数组中值“3”的位置,方法是使用 array_search

或者按如下所示更改您的 SQL:

select
@rownumber:=1+@rownumber as 'rownumber',
id_field, number_field
from yourtable, (SELECT @rownumber:=0) rownumber order by number_field DESC

这将添加一个附加列 'rownumber',它提供每行的编号

If you're returning the resultset via PHP, you can use PHP to determine the position of the value '3' within the array for the ID field by using array_search

Or change your SQL as follows:

select
@rownumber:=1+@rownumber as 'rownumber',
id_field, number_field
from yourtable, (SELECT @rownumber:=0) rownumber order by number_field DESC

This will add an additional column 'rownumber' which provides the number of each row

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文