暂无图片
MogDB/openGauss如何实现自增主键
最近更新:2023-11-06 16:39:54

自增主键是我们在设计数据库表结构时经常使用的主键生成策略,主键的生成可以完全依赖数据库,无需人为干预,在新增数据的时候,我们只需要将主键的值设置为default,数据库就会为我们自动生成一个主键值。

MySQL主键自增使用AUTO_INCREMENT关键字,PostgreSQL自增使用SERIAL关键字或者序列。 而MogDB/openGauss里兼容两种语法。AUTO_INCREMENT在MogDB-3.1.0/openGauss-5.0.0以上适配。

所以使用MySQL和PG的数据库迁移到MogDB/openGauss的时候,都可以完美地适配。 下文会针对MogDB/openGauss里几种自增主键的实现进行一个简单的验证。

一、MySQL的方式(AUTO_INCREMENT)

注意,AUTO_INCREMENT功能,只有在MogDB/openGauss的B兼容模式下才可以使用,否则将会有如此下的提示。

MogDB=#  SELECT current_database(); 
 current_database 
------------------
 postgres
(1 row)

MogDB=# \l postgres
                                 List of databases
   Name   | Owner | Encoding | Collate | Ctype | Access privileges | Compatibility 
----------+-------+----------+---------+-------+-------------------+---------------
 postgres | om5   | UTF8     | C       | C     |                   | A
(1 row)

MogDB=# CREATE TABLE test_create_autoinc(id bool auto_increment primary key, name varchar(200),a int) auto_increment=1;
ERROR:  auto_increment is supported only in B-format database
MogDB=# 

正确的使用方式如下:

MogDB=# create database db_mysql with dbcompatibility ='B';
......