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)
   -> );
Query OK, 0 rows affected (0.74 sec)

使用 insert 命令在表中插入一些记录。查询如下 −

mysql> insert into RowNumberDemo values(10,'John');
Query OK, 1 row affected (0.14 sec)
mysql> insert into RowNumberDemo values(50,'Carol');
Query OK, 1 row affected (0.20 sec)
mysql> insert into RowNumberDemo values(100,'Sam');
Query OK, 1 row affected (0.20 sec)
mysql> insert into RowNumberDemo values(150,'Mike');
Query OK, 1 row affected (0.54 sec)
mysql> insert into RowNumberDemo values(210,'Bob');
Query OK, 1 row affected (0.58 sec)

使用 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)

更新于: 30-7 月-2019

647 次浏览

开启你的 职业生涯

完成课程,获得认证

开始
广告