mysql 对表进行排序并获取行位置
我在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
可以更改上述查询,将
ID
替换为您需要的任何内容。然而,对于简单的使用,
ORDER BY number DESC
更好并且经过优化。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.如果有用的话尝试这个查询。
谢谢。
try this query if usefull.
Thanks.
如果您通过 PHP 返回结果集,则可以使用 PHP 来确定 ID 字段数组中值“3”的位置,方法是使用 array_search
或者按如下所示更改您的 SQL:
这将添加一个附加列 '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:
This will add an additional column 'rownumber' which provides the number of each row