MySQL - Select row number of a record

核能气质少年 提交于 2019-12-21 20:05:06

问题


I have a table in MySQL populated as follows. Now I need to select the row number of a record in its sorted order. For example, the row number of words starting with 'c' should be 4.

Words
=====
coffee
banana
apple
cherry
blackberry

I tried the following query, but I get wrong results. Here dict is the table name and words is the column name.

SELECT @rownum:=@rownum + 1 id FROM (SELECT * FROM dict ORDER BY words) d,(SELECT @rownum:=0) r WHERE d.words LIKE CONCAT('c','%')

For the above query, I am getting the row numbers for the outer query. But I want the row numbers of the internal query. I do not know how to get that.

Any help is appreciated. Thanks.


回答1:


Try this perhaps:

SET @rownum = 0;
SELECT id 
FROM (SELECT *, @rownum:=@rownum + 1 AS id FROM dict ORDER BY words) d
WHERE d.words LIKE CONCAT('c','%')

As single query, try this:

SELECT id 
FROM (SELECT *, @rownum:=@rownum + 1 AS id FROM dict, (SELECT @rownum:=0) r ORDER BY words) d
WHERE d.words LIKE CONCAT('c','%')


来源:https://stackoverflow.com/questions/8235003/mysql-select-row-number-of-a-record

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!