全局唯一数字序列

最近更新时间: 2024-06-12 15:06:00

TDSQL支持全局唯一数字序列(auto_increment)的使用;暂时仅保证自增字段全局唯一和递增性,但是不保证单调递增(即按时间顺序的绝对递增性)。 全局唯一数字序列(auto_increment) 长 8 字节,最大为 18446744073709551616,因此,您无需担心该值溢出。

注意:

select last_insert_id()命令只能与Shard表和广播表的自增字段一起使用,不支持与Noshard表的使用。

示例:

创建自增字段的表:
mysql> DROP TABLE IF EXISTS auto_inc;

mysql> create table auto_inc (a int,b int,c int auto_increment,d int,key auto(c),primary key p(a,d)) shardkey=d;
Query OK, 0 rows affected (0.12 sec)

插入自增字段的分表:
mysql> insert into auto_inc (a,b,d,c) values(1,2,3,0),(1,2,4,0);
Query OK, 2 rows affected (0.05 sec)
Records: 2  Duplicates: 0  Warnings: 0

MySQL [test]> select * from auto_inc;
+---+------+------+---+
| a | b    | c    | d |
+---+------+------+---+
| 1 |    2 | 1008 | 4 |
| 1 |    2 | 1007 | 3 |
+---+------+------+---+
2 rows in set (0.00 sec)

自增字段的空洞处理:
由于 auto_increment 仅保证自增字段全局唯一和递增性,如果在节点调度切换、重启等过程中,自增长字段中间会出现空洞,例如:
MySQL [test]>insert into auto_inc (a,b,d,c) values(11,12,13,0),(21,22,23,0);
Query OK, 2 rows affected (0.00 sec)

MySQL [test]> select * from auto_inc;
+----+------+------+----+
| a  | b    | c    | d  |
+----+------+------+----+
| 11 |   12 | 1009 | 13 |
| 21 |   22 | 1010 | 23 |
|  1 |    2 | 1008 |  4 |
|  1 |    2 | 1007 |  3 |
+----+------+------+----+
4 rows in set (0.00 sec)

可更改当前值,命令如下:
MySQL [test]> alter table auto_inc auto_increment=100;
Query OK, 0 rows affected (0.03 sec)

目前不支持通过insert into auto_inc set c=100 语法插入数据,如果用户要指定自增的值,需要使用以下语法:
insert into auto_inc (a,b,d,c) values(300,400,100,500);

通过select last_insert_id()命令获取自增值,如果用户不指定自增值,可以通过select last_insert_id()命令获取,暂不支持直接从Insert返回包获取,详见如下:
MySQL [test]> insert into auto_inc (a,b,d,c) values(5,6,7,8),(11,12,14,19);
Query OK, 2 rows affected (0.00 sec)
Records: 2 Duplicates: 0 Warnings: 0

MySQL [test]> select * from auto_inc;
+-----+------+------+-----+
| a   | b    | c    | d   |
+-----+------+------+-----+
|  11 |   12 | 1009 |  13 |
|   5 |    6 |    8 |   7 |
|  11 |   12 |   19 |  14 |
| 300 |  400 |  500 | 100 |
|  21 |   22 | 1010 |  23 |
|   1 |    2 | 1008 |   4 |
|   1 |    2 | 1007 |   3 |
+-----+------+------+-----+
7 rows in set (0.00 sec)

MySQL [test]> select last_insert_id();
+------------------+
| last_insert_id() |
+------------------+
| 1009             |
+------------------+
1 row in set (0.00 sec)