问题
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