POSTGRESQL和 MYSQL的自增字段比较

前端之家收集整理的这篇文章主要介绍了POSTGRESQL和 MYSQL的自增字段比较前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
最近学习PGsql。来比较一下他和MysqL自增字段的不同点。
1、自增序列。MysqL从最后一个ID自增。
测试数据。

1, I love this girl.
2.
3is my girl.
4is your girl
.
MysqL
MysqL> create database test;
Query OKrow affected (0.10 sec)

MysqL> use test
Database changed
MysqLtable t(id int not null auto_increment primary key-> username char(20) null)rows affected .02 sec)
MysqL> load data infile '/tmp/test.sql' into table t fields terminated by ','.00 sec)
Records: 4 Deleted: 0 Skipped: 0 Warnings: 0

MysqLselect * from t;
+
----+-------------------+

| id | username |
| 1 | I love this girl. | 2 | I hate this girl| 3 | She | 4 is your girl----+-------------------+

4 rows in set insert into t values (6'This is inserted'into t(usernamevalues('This is last'| 6 | This is inserted | 7 is last ----+-------------------+


MysqLtruncate ----+--------------+

----+--------------+

3 )

PGsql从1开始逐个尝试。

[root@localhost ~]# psql -Upostgres -hlocalhost
。。。
postgres=# CREATE DATABASE
postgres\c test
You are now connected to database "test".
test(id serial ;
NOTICE: TABLE will create implicit sequence "t_id_seq" for serial column "t.id"
TABLE
test\d tTable "public.t"
Column | Type | Modifiers
----------+---------------+------------------------------------------------

id integer null default nextval't_id_seq'::regclass)
username | characternull
test# copy t from with csv;
COPY 4
test;
id | username
----+----------------------

1 .
2 .
3 .
4 .
(4 rows)

testINSERT 0 1
test;
ID1重复
ERROR: duplicate key violates unique constraint "t_pkey"
test;
ID2重复
ERROR;
。。。
ID5没有。插入
;
ID6又重复
ERROR..
.
6 is inserted
5 is last
7 is last
8 is last
9 is last
(9 )
看一下DELETE操作。
testdelete DELETE 9
test----+----------------------

10 is last
11 is last
12 (3 )
这个和MysqL一样的。
TRUNCATE虽然和MysqL一样可以快速清空表数据。可是ID还是从最后一个开始增加的,如果想从1开始的话,就得用setval函数来设置。
testTRUNCATE ----+----------------------

13 is last
14 is last
15 )
至于怎么从1重新开始。还在学习中。。。



2、得到刚刚插入的自增ID。

MysqL里面:
MysqLselect last_insert_id(------------------+

| last_insert_id------------------+

1 row )
在POSTGREsql里面:

testdrop table t
testDROP "t.id"
NOTICETABLE / PRIMARY KEY will index "t_pkey" for table "t"
\d t
null
Indexes:
KEY(id'This is test name'is test name
(1 rowselect currval;
currval
---------

1
#
3、设置自增ID的开始值。
MysqL:

MysqLalter table t auto_increment = 3.01 sec: 1 Duplicates----+--------------+

2 POSTGREsql:

t_girlselect setvalfalse;
setval
--------

1
)

Time: 19.554 ms
t_girl'wangwei''meimei'INSERT 0 2
Time: 1.882 ms
t_girl| wangwei
2 | meimei
(2 : 0.598 ms
原文链接:https://www.f2er.com/postgresql/197413.html

猜你在找的Postgre SQL相关文章