mysql行号order by,MySQL在ORDER BY中获得行位置

With the following MySQL table:

+-----------------------------+

+ id INT UNSIGNED +

+ name VARCHAR(100) +

+-----------------------------+

How can I select a single row AND its position amongst the other rows in the table, when sorted by name ASC. So if the table data looks like this, when sorted by name:

+-----------------------------+

+ id | name +

+-----------------------------+

+ 5 | Alpha +

+ 7 | Beta +

+ 3 | Delta +

+ ..... +

+ 1 | Zed +

+-----------------------------+

How could I select the Beta row getting the current position of that row? The result set I'm looking for would be something like this:

+-----------------------------+

+ id | position | name +

+-----------------------------+

+ 7 | 2 | Beta +

+-----------------------------+

I can do a simple SELECT * FROM tbl ORDER BY name ASC then enumerate the rows in PHP, but it seems wasteful to load a potentially large resultset just for a single row.

解决方案

Use this:

SELECT x.id,

x.position,

x.name

FROM (SELECT t.id,

t.name,

@rownum := @rownum + 1 AS position

FROM TABLE t

JOIN (SELECT @rownum := 0) r

ORDER BY t.name) x

WHERE x.name = 'Beta'

...to get a unique position value. This:

SELECT t.id,

(SELECT COUNT(*)

FROM TABLE x

WHERE x.name <= t.name) AS position,

t.name

FROM TABLE t

WHERE t.name = 'Beta'

...will give ties the same value. IE: If there are two values at second place, they'll both have a position of 2 when the first query will give a position of 2 to one of them, and 3 to the other...

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值