要在 MySQL 中创建序列,可以在列上使用 auto_increment。它从 值1,并且每插入一条记录就加1。
首先,借助CREATE table 创建一个表。查询如下 -
mysql> CREATE table SequenceDemo -> ( -> SequenceId int auto_increment, -> primary key(SequenceId) -> ); Query OK, 0 rows affected (1.22 sec)
创建表后,可以使用insert命令插入记录 给出如下 -
mysql> INSERT into SequenceDemo values(); Query OK, 1 row affected (0.19 sec) mysql> INSERT into SequenceDemo values(); Query OK, 1 row affected (0.14 sec) mysql> INSERT into SequenceDemo values(); Query OK, 1 row affected (0.10 sec) mysql> INSERT into SequenceDemo values(); Query OK, 1 row affected (0.12 sec) mysql> INSERT into SequenceDemo values(); Query OK, 1 row affected (0.09 sec)
插入记录后,可以借助select语句来显示记录,即 给出如下 -
mysql> SELECT * from SequenceDemo;
以下是获得的输出 -
+------------+ | SequenceId | +------------+ | 1 | | 2 | | 3 | | 4 | | 5 | +------------+ 5 rows in set (0.00 sec)
可以在alter命令的帮助下设置序列。其语法如下 如下 -
alter table yourTableName auto_increment=Somevalue;
Now, the above syntax is used in the following query to set the sequence value as 如下 -
mysql> alter table SequenceDemo auto_increment = 500; Query OK, 0 rows affected (0.17 sec) Records: 0 Duplicates: 0 Warnings: 0
之后,记录从表中的值 500 开始插入。下面给出 -
mysql> INSERT into SequenceDemo values(); Query OK, 1 row affected (0.15 sec) mysql> INSERT into SequenceDemo values(); Query OK, 1 row affected (0.15 sec) mysql> INSERT into SequenceDemo values(); Query OK, 1 row affected (0.05 sec)
All the records can be displayed with the select statement as 如下 -
mysql> SELECT * from SequenceDemo;
输出如下
+------------+ | SequenceId | +------------+ | 1 | | 2 | | 3 | | 4 | | 5 | | 500 | | 501 | | 502 | +------------+ 8 rows in set (0.00 sec)
从上面的输出可以看出,在5条记录之后,序列id从500开始,为 增加 1。
以上是如何在 MySQL 中创建和使用序列?的详细内容。更多信息请关注PHP中文网其他相关文章!