POSTGRESQL 插入數據時主鍵沖突異常


異常:
表INSERT不了數據。
postgres=# insert into t_rows(name) values('b');
ERROR:  duplicate key value violates unique constraint "t_rows_pkey"
DETAIL:  Key (id)=(2) already exists

表結構如下:

postgres=# \d t_rows;
                                Table "public.t_rows"
 Column |         Type         |                      Modifiers                      
--------+----------------------+-----------------------------------------------------
 id     | integer              | not null default nextval('t_rows_id_seq'::regclass)
 name   | character varying(9) | 
Indexes:
    "t_rows_pkey" PRIMARY KEY, btree (id)
ID為自增列, 但插入數據的時候插入不了。
檢查表記錄:
postgres=# select * from t_rows where id=2;
 id | name 
----+------
  2 | a
(1 row)
表記錄確實是有,為何在自增長時並沒有辦法生成正確的ID值呢?
在PG里面的自增長主鍵是利用的序列,查看序列當前值:
postgres=# select currval('t_rows_id_seq');
 currval 
---------
       2
(1 row)
分析:
表里已經有ID為2的數據了, 序列的當前值依舊為2,所以這里數據是無法INSERT的。
為何會這樣呢?
在POSTGRESQL中當你COPY記錄到表時, 或者插入數據時帶了自增ID等都不會影響序列的變化, 所以導致了序列與表的記錄不一致的情況。
 
解決方案:
將序列的值更新為比表記錄最大值加1即可:
postgres=# SELECT setval('t_rows_id_seq', (SELECT max(id) FROM t_rows));
 setval 
--------
     11
(1 row)

再次INSERT進數據:

postgres=# insert into t_rows(name) values('b');
INSERT 0 1

已成功INSERT進數據,問題解決。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM