MySQL row number

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-22 09:36:33

问题


Say I have a MySQL query, for example:

SELECT id, name, surname FROM employees ORDER BY id

The result woud be:

id    name    surname
 1     Peter   Smith
 2     John    Banjo
...
 1384  Will    Levenstein

While this is an ordered query, I can always assume (as long as I don't change the table) that John Banjo will come out second.

Now what if my query was

SELECT id, name, surname FROM employees WHERE name = 'John' AND surname = 'Banjo'

Could I somehow get what the row number would be in the first query? I'm trying to do this in a much more complicated, but always ordered query, is there any way to archieve this?


回答1:


 SELECT x.id, x.name, x.surname, x.rownum
 FROM (
      SELECT @rownum:=@rownum+1 rownum, t.*
      FROM (SELECT @rownum:=0) r, employees t
      ORDER BY Id
 ) x
 WHERE x.name = 'John' 
 AND x.surname = 'Banjo'


来源:https://stackoverflow.com/questions/3576304/mysql-row-number

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