SQLite3函数:last_insert_rowid()

-- TOC --

SQL这种操作数据库的接口语言中,也有函数,用于对select返回的值进行某种计算。在SQLite3中,有一个函数其实有点特别,它就是 last_insert_rowid() 。

为什么说它特别?

因为 rowid 是一个SQLite3内置的关键词,任何一个table中,都隐藏的一个rowid,甚至是独立于 primary key 的存在。

sqlite> .schema ab
CREATE TABLE ab(id int primary key, sn int);
sqlite> select * from ab;
id  sn
--  --
1   1
2   2
    2
    2
    2
    2
    2
sqlite> select rowid, id, sn from ab;
rowid  id  sn
-----  --  --
1      1   1
2      2   2
3          2
4          2
5          2
6          2
7          2

只有当table的主键使用 integer primary key 定义的时候,rowid与这个primary key重合。这是一个在SQLite3中很重要的table设计细节,能够带来很多好处,性能,存储,没有额外的index等。

sqlite> create table ac(id integer primary key, sn int);
sqlite> insert into ac values (null,1);
sqlite> insert into ac values (null,1);
sqlite> insert into ac values (null,1);
sqlite> insert into ac values (null,1);
sqlite> insert into ac values (null,1);
sqlite> select rowid,id,sn from ac;
id  id  sn
--  --  --
1   1   1
2   2   1
3   3   1
4   4   1
5   5   1
sqlite> select * from ac;
id  sn
--  --
1   1
2   1
3   1
4   1
5   1

说了这么多,就是想说,last_insert_rowid() 函数,得到的就是这个rowid!

sqlite> select * from ac;
id  sn
--  --
1   1
2   1
3   1
4   1
5   1
sqlite> select last_insert_rowid();
last_insert_rowid()
-------------------
5

个人认为,由于table之间的关联关系很可能会通过这个rowid来进行,用last_insert_rowid函数会很方便。如果没有这个函数,正常的逻辑就是insert后再用某些唯一的condition来select,找出这个id,会比较费劲。

下面是从网上摘的一段关于SQLite3支持的函数,留个参考吧:

算术函数
    abs(X) 返回给定数字表达式的绝对值
    max(X,Y[,...]) 返回表达式的最大值
    min(X,Y[,...]) 返回表达式的最小值
    random(*) 返回随机数
    round(X[,Y]) 返回数字表达式并四舍五入为指定的长度或精度
字符处理函数
    length(X) 返回给定字符串表达式的字符个数
    lower(X) 将大写字符数据转换为小写字符数据后返回字符表达式
    upper(X) 返回将小写字符数据转换为大写的字符表达式
    substr(X,Y,Z) 返回表达式的一部分
    randstr()  
    quote(A)  
    like(A,B) 确定给定的字符串是否与指定的模式匹配
    glob(A,B)  
条件判断函数
    coalesce(X,Y[,...])  
    ifnull(X,Y)  
    nullif(X,Y)  
集合函数
    avg(X) 返回组中值的平均值
    count(X) 返回组中项目的数量
    max(X) 返回组中值的最大值
    min(X) 返回组中值的最小值
    sum(X) 返回表达式中所有值的和
其他函数
    typeof(X) 返回数据的类型
    last_insert_rowid() 返回最后插入的数据的ID
    sqlite_version(*) 返回SQLite的版本
    change_count() 返回受上一语句影响的行数
    last_statement_change_count()

本文链接:https://cs.pynote.net/sf/sqlite/202203201/

-- EOF --

-- MORE --