如何在查询中使用MySQL ROW_NUMBER函数

4

我正在学习MySQL ROW_NUMBER()函数以及如何使用它来为结果集中的每一行生成一个顺序号。

目前我的尝试:

SELECT e.*, 
ROW_NUMBER() 
OVER(PARTITION BY e.examid ORDER BY e.examid) AS id 
from exam e

当我运行这个查询时,出现了一系列错误:

3 errors were found during analysis.

An alias was previously found. (near "id" at position 68)
An alias was expected. (near " " at position 67)
Unexpected token. (near "id" at position 68)

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(PARTITION BY examid ORDER BY examid) as id from exam LIMIT 0, 25' at line 1

我该怎样着手处理?


MySQL 8.0支持ROW_NUMBER。 - Lukasz Szozda
2
更重要的是,MySQL < 8.0 不支持 ROW_NUMBER。你使用的是哪个版本?SELECT @@version; - Bill Karwin
@BillKarwin,5.7.14 - Olajumoke Ademilade
所以,这就解释了为什么在MySQL 8.0之前不可用的功能无法使用。 - Bill Karwin
https://dev59.com/jV8e5IYBdhLWcg3wCWx2#27150629 - Waqar
2个回答

1

我遇到了同样的问题。在我的情况下,这种语法是有效的:

SELECT
    (ROW_NUMBER() OVER (ORDER BY id)) row_number, Field1, Field2
FROM
    myTable
ORDER BY
    id

附加说明:select version() 返回 10.3.20-MariaDB-log

括号 - 这就是我需要添加的别名。太好了,谢谢! - Hebe

0

将I'd更改为其他内容,因为select *语句将返回一个id,并且会与该I'd(AS id)发生冲突。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接