金仓数据库KingbaseES 新兼容——last_insert_id()
1. MySQL中的last_insert_id()
|
数据库 |
函数名 |
返回值类型 |
调用方式 |
函数定义 |
函数功能 |
函数间的影响 |
|
MySQL |
last_insert_id() |
bigint unsigned |
select last_insert_id(); |
获取最近插入的元祖的自增字段值 |
返回一条语句中第一个成功插入元组使用自增列生成的值 |
ast_insert_id(expr);的返回值会影响last_insert_id();的返回值,在没有实现’返回一条语句中第一个成功插入元组使用自增列生成的值’时,last_insert_id();的返回值与last_insert_id(expr);一致 |
|
last_insert_id(expr) |
bigint unsigned |
select last_insert_id(expr); |
返回expr |
1、返回expr的值 2、使得在下一次系统自增值产生之前调用last_insert_id()也返回expr |
last_insert_id(expr)的特性
①last_insert_id(expr)函数用于返回表达式的值,用于设置last_insert_id()的值;
②因为mysql中expr的类型为bigint unsigned,expr为负数时,返回值为无穷大;
③在last_insert_id(expr)调用后立即调用select last_insert_id(),select last_insert_id()的返回结果与前面last_insert_id(expr)的返回结果一致;
④插入expr为NULL时,函数返回NULL,插入expr为字符串时,函数返回0
⑤插入expr为NULL后,调用last_insert_id(),函数返回0;
⑥MySQL内部存在类型的隐式转换,expr不同的类型有不同的隐式转换。
last_insert_id()的特性
语句级:
last_insert_id()返回值与表无关;
last_insert_id()用于返回一条语句中第一个成功插入元组使用自增列生成的值;
语句块级:
调用存储过程插入元组,last_insert_id()返回一条语句中第一个成功插入元组使用自增列生成的值;
调用函数插入元组,在函数内部调用last_insert_id(),返回一条语句中第一个成功插入元组使用自增列生成的值,在函数外部调用last_insert_id(),返回旧值;
对于更改值的函数,当函数结束时,值将恢复,因此不会看到更改的值;
触发器内部调用last_insert_id()返回值与触发器外部调用last_insert_id()返回值不一致;
对于更改值的触发器,当触发器结束时,值将恢复,因此不会看到更改的值;
事物级:
手动事务回滚,last_insert_id()函数的返回值不会回滚;
会话级:
last_insert_id()的返回值是当前会话所产生的自增值,不同的会话中last_insert_id()的返回值可能不一样;
2. 金仓数据库KingbaseES兼容功能
编辑
函数调用:
select/call/exec last_insert_id();
select/call/exec last_insert_id(expr);
KES中call和exec为兼容Oracle数据库所实现的功能,MySQL数据库并不支持。但是在KES-MySQL中支持用call和exec调用函数,因此在此调用函数的方式选择用select、call、exec三种方式。
限制与约束:
- 查询和插入所使用的connection对象必须是同一个,否则返回值是不可预料的;
- 一个表只能有一个自增列。
- insert ignore与insert...on duplicate key update会造成自增值跳号,致使last_insert_id()函数返回值跳号;
- last_insert_id(expr)函数,不同的参数类型,函数返回结果不同,这属于MySQL数据库自身实现的隐式类型转换,KES-MySQL并未完全同步,在此需求中并不实现隐式类型转换的需求。
- last_insert_id(expr)函数的调用会影响last_insert_id()函数的返回值,
编辑
3. 金仓数据库KingbaseES的实现
语法试例:
|
select/call/exec last_insert_id(); select/call/exec last_insert_id(3); select/call/exec last_insert_id(3+3*3); test=# select last_insert_id(); last_insert_id ---------------- 0 (1 row) test=# select last_insert_id(3); last_insert_id ---------------- 3 (1 row) test=# select last_insert_id(3+3*3); last_insert_id ---------------- 12 (1 row) |
新兼容的last_insert_id()函数,保持了代码的兼容性,使迁移时更加平滑和简单,减少迁移过程中的工作量和风险,降低学习新数据库系统的成本,减少了重新学习和适应新系统的时间和精力。




