如何在 MySQL 中插入序列号?
你可以使用会话变量在 MySQL 中插入序列号。语法如下所示 −
SELECT @anyVariableName − = anyIntegerValue; UPDATE yourTableName SET yourColumnName = @anyVariableName − = @anyVariableName+IncrementStep;
为了理解上述语法,让我们创建一个表。创建表的查询如下所示 −
mysql> create table SequentialNumberDemo -> ( -> SequentialNumber int not null -> ); Query OK, 0 rows affected (0.84 sec)
使用 insert 命令在表中插入记录。该查询如下所示 −
mysql> insert into SequentialNumberDemo values(100); Query OK, 1 row affected (0.11 sec) mysql> insert into SequentialNumberDemo values(10); Query OK, 1 row affected (0.22 sec) mysql> insert into SequentialNumberDemo values(9); Query OK, 1 row affected (0.15 sec) mysql> insert into SequentialNumberDemo values(60); Query OK, 1 row affected (0.11 sec) mysql> insert into SequentialNumberDemo values(50); Query OK, 1 row affected (0.14 sec) mysql> insert into SequentialNumberDemo values(40); Query OK, 1 row affected (0.13 sec)
使用 select 语句显示表中的所有记录。该查询如下所示 −
mysql> select *from SequentialNumberDemo;
以下为输出 −
+------------------+ | SequentialNumber | +------------------+ | 100 | | 10 | | 9 | | 60 | | 50 | | 40 | +------------------+ 6 rows in set (0.00 sec)
查看以上输出,数字并不按照顺序。这里有一个从 1 开始获取序列号的查询。首先,设置序列 −
mysql> select @sequence: = 0;
输出 −
+---------------+ | @sequence:= 0 | +---------------+ | 0 | +---------------+ 1 row in set (0.03 sec)
现在,更新查询并从 1 开始序列 −
mysql> update SequentialNumberDemo set SequentialNumber = @sequence − = @sequence+1; Query OK, 6 rows affected (0.15 sec) Rows matched − 6 Changed − 6 Warnings − 0
再次检查表记录。该查询如下所示 −
mysql> select *from SequentialNumberDemo;
以下为输出 −
+------------------+ | SequentialNumber | +------------------+ | 1 | | 2 | | 3 | | 4 | | 5 | | 6 | +------------------+ 6 rows in set (0.00 sec)
广告