一. Mysql 自增列
众所周知, mysql 有自增列功能。
Mysql 中每张表只能有一个自增列,并且自增列必须是主键或者唯一键。
mysql> create table test2(id int not null auto_increment); ERROR 1075 (42000): Incorrect table definition; there can be only one auto column and it must be defined as a key mysql> create table test2(id int not null auto_increment primary key); Query OK, 0 rows affected (0.01 sec) |
Mysql 插入空值,可以看到是允许的,默认会用自增列值插入。
mysql> insert into test2 values(); Query OK, 1 row affected (0.01 sec)
mysql> select * from test2; +----+ | id | +----+ | 1 | +----+ 1 row in set (0.00 sec) |
Mysql 也是允许插入的值不连续
mysql> insert into test2 values(3); Query OK, 1 row affected (0.00 sec)
mysql> select * from test2; +----+ | id | +----+ | 1 | | 3 | +----+ 2 rows in set (0.00 sec) |
表加一列,显式插入新增列,自增列会隐式地从当前最大值自增。
mysql> insert into test2(b) values(4); Query OK, 1 row affected (0.00 sec)
mysql> select * from test2; +----+------+ | id | b | +----+------+ | 1 | NULL | | 3 | NULL | | 4 | 4 | +----+------+ 3 rows in set (0.00 sec) |
二. Oracle 自增列
Oracle 在 12c 之前的版本,自增列功能只能通过序列 + 触发器的方式实现。 12c 版本终于迎来了这个新功能。
自增列语法
建表
SQL> CREATE TABLE test1 ( 2 id int GENERATED ALWAYS AS IDENTITY |