Getting rank of a row in mysql query

我们两清 提交于 2019-12-01 04:32:14

问题


I was using this query to assign rank to every name according to the votes they have got, but it returns with the error :

1248 - Every derived table must have its own alias

Here is my code:

SELECT @rownum:=@rownum+1 AS rank, name, vote 
FROM table, (SELECT @rownum:=0) ORDER BY vote DESC

On modifying the query to this :-

SELECT @rownum:=@rownum+1 AS rank, name, vote 
FROM table ORDER BY vote DESC

I get as expected rank of the queries as NULL. Any help , how to get rank at first place ?

NOTE: I am not looking for any alternative solution. Just trying to do it in the query itself.


回答1:


The error is pretty clear. Every derived table must have its own alias. You need to alias the (SELECT @rownum := 0) like so:

SELECT 
  @rownum := @rownum + 1 AS rank, 
  name,
  vote 
FROM table, (SELECT @rownum := 0) t --This what you were missing an alias
ORDER BY vote DESC

SQL Fiddle Demo



来源:https://stackoverflow.com/questions/13209227/getting-rank-of-a-row-in-mysql-query

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