在MySQL中等效于ROW_NUMBER()进行插入吗?
MySQL中没有等效的ROW_NUMBER()进行插入,但是您可以借助变量来实现。语法如下-
SELECT (@yourVariableName:=@yourVariableName + 1) AS `anyAliasName`, yourColumnName1,yourColumnName2,...N FROM yourTableName ,(SELECT @yourVariableName:=0) AS anyAliasName;
为了理解上述语法,让我们创建一个表。创建表的查询如下-
mysql> create table RowNumberDemo -> ( -> UserId int, -> UserName varchar(20) -> );
使用insert命令在表中插入一些记录。查询如下-
mysql> insert into RowNumberDemo values(10,'John'); mysql> insert into RowNumberDemo values(50,'Carol'); mysql> insert into RowNumberDemo values(100,'Sam'); mysql> insert into RowNumberDemo values(150,'Mike'); mysql> insert into RowNumberDemo values(210,'Bob');
使用select语句显示表中的所有记录。查询如下-
mysql> select *from RowNumberDemo;
以下是输出-
+--------+----------+ | UserId | UserName | +--------+----------+ | 10 | John | | 50 | Carol | | 100 | Sam | | 150 | Mike | | 210 | Bob | +--------+----------+ 5 rows in set (0.00 sec)
这是获取类似ROW_NUMBER的查询-
mysql> SELECT -> (@ROW_NUMBER:=@ROW_NUMBER + 1) AS `ROW_NUMBER`, UserId,UserName -> FROM -> RowNumberDemo,(SELECT @ROW_NUMBER:=0) AS t;
以下是输出-
+------------+--------+----------+ | ROW_NUMBER | UserId | UserName | +------------+--------+----------+ | 1 | 10 | John | | 2 | 50 | Carol | | 3 | 100 | Sam | | 4 | 150 | Mike | | 5 | 210 | Bob | +------------+--------+----------+ 5 rows in set (0.03 sec)