小編給大家分享一下postgresql有rowid函數嗎,希望大家閱讀完這篇文章后大所收獲,下面讓我們一起去探討吧!
oracle中可以通過rowid定位到一條數據。索引掃描就是先根據查詢條件的到對應數據的rowid,然后通過rowid得到數據,也可以直接使用rowid來查詢數據,比如select * from tbl where rowid=xxx; 在沒有行遷移的情況下,rowid是固定不變的。
在pg中索引掃描是先查詢到數據的ctid,然后根據ctid去得到相應的數據。但是ctid和oracle中的rowid并不完全相同,因為pg中多版本的原因,ctid是會發生變化的,例如:
bill=# select ctid,* from t1 limit 5; ctid | id --------+---- (0,1) | 1 (0,2) | 2 (0,3) | 3 (0,4) | 4 (0,5) | 5 (5 rows) bill=# update t1 set id=111 where id =1; UPDATE 1 bill=# vacuum ANALYZE t1; VACUUM bill=# select ctid,* from t1 limit 5; ctid | id --------+---- (0,2) | 2 (0,3) | 3 (0,4) | 4 (0,5) | 5 (0,6) | 6 (5 rows)
那在pg中如何實現類似rowid類似的功能呢?
—方法一:sequence 唯一標識
bill=# create table tbl (rowid serial8 not null, c1 int, c2 int); CREATE TABLE bill=# create unique index idx_tbl_1 on tbl(rowid); CREATE INDEX bill=# insert into tbl (c1,c2) values (1,2); INSERT 0 1 bill=# insert into tbl (c1,c2) values (1,2); INSERT 0 1 bill=# insert into tbl (c1,c2) values (1,2); INSERT 0 1 bill=# select * from tbl; rowid | c1 | c2 ------+----+---- 1 | 1 | 2 2 | 1 | 2 3 | 1 | 2 (3 rows)
—方法二:identify列
bill=# create table tbl (rowid int8 GENERATED ALWAYS AS IDENTITY not null, c1 int, c2 int); create unique index idx_tbl_1 on tbl(rowid); CREATE TABLE bill=# create unique index idx_tbl_1 on tbl(rowid); CREATE INDEX bill=# insert into tbl (c1,c2) values (1,2); INSERT 0 1 bill=# insert into tbl (c1,c2) values (1,2); INSERT 0 1 bill=# insert into tbl (c1,c2) values (1,2); INSERT 0 1 bill=# select * from tbl; rowid | c1 | c2 ------+----+---- 1 | 1 | 2 2 | 1 | 2 3 | 1 | 2 (3 rows)
—方法三:oid
bill=# /dT oid List of data types Schema | Name | Description -----------+------+------------------------------------------- pg_catalog | oid | object identifier(oid), maximum 4 billion (1 row)
不過oid不適合存儲超過40億條記錄的表。
postgres=# create table tbl (c1 int, c2 int) with oids; CREATE TABLE postgres=# create unique index idx_tbl_oid on tbl(oid); CREATE INDEX postgres=# insert into tbl (c1,c2) values (1,2); INSERT 168528 1 postgres=# insert into tbl (c1,c2) values (1,2); INSERT 168529 1 postgres=# insert into tbl (c1,c2) values (1,2); INSERT 168530 1 postgres=# select oid,* from tbl; oid | c1 | c2 --------+----+---- 168528 | 1 | 2 168529 | 1 | 2 168530 | 1 | 2 (3 rows)
不過需要注意的是,在pg12中已經不支持create table xxx with oids這種語法了。
bill=# create table tbl (c1 int, c2 int) with oids; psql: ERROR: syntax error at or near "oids" LINE 1: create table tbl (c1 int, c2 int) with oids;
pg12中是將oid作為一種數據類型來使用:
bill=# create table tbl(oid oid,c1 int,c2 int); CREATE TABLE
看完了這篇文章,相信你對postgresql有rowid函數嗎有了一定的了解,想了解更多相關知識,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。