在MySQL中选择行号

g0czyy6m  于 2022-12-03  发布在  Mysql
关注(0)|答案(2)|浏览(124)

我想从MySQL表中获取每一行的行号。我已经阅读了这个article并尝试了下面建议的select语句,

SELECT @rownum:=@rownum + 1 as row_number, 
       t.*
FROM ( 
   select * from myTable
) t,
(SELECT @rownum := 0) r

但是当我在Dbeaver中运行时,我遇到了如下语法错误,

SQL Error [1064] [42000]: 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 'row_number, 
       t.*
FROM ( 
   select * from myTable
) t,
(SELECT @r' at line 1

有人能帮忙吗?我是MySQL新手。我使用的是8.0版本。一旦测试完毕,我基本上会在我的Apache Spark Code中使用这个select

bkhjykvo

bkhjykvo1#

请使用以下选项:

SELECT @rownum:=@rownum + 1 as row_num, 
       t.*
FROM ( 
   select * from myTable
) t,
(SELECT @rownum := 0) r;

row_number是mysql的保留关键字,您不能将其用作别名或其他用途。

pbossiut

pbossiut2#

试试这个。

SELECT *,   
        ROW_NUMBER() OVER(PARTITION BY 'some column' ) AS row_num  
    FROM my_table

https://www.javatpoint.com/mysql-row_number-function)(英文)

相关问题