鍍金池/ 問(wèn)答/數(shù)據(jù)庫(kù)/ postgresql 批量插入

postgresql 批量插入

有兩個(gè)小問(wèn)題:
1、postgresql 在執(zhí)行批量時(shí)插入時(shí)間是一致的,有沒(méi)有辦法讓他們不一致?
2、當(dāng)庫(kù)中已經(jīng)存在重復(fù)數(shù)據(jù)時(shí),整個(gè)執(zhí)行操作就失敗了。比如一次插入10條,其中有一條是庫(kù)中重復(fù)了,整個(gè)10條都沒(méi)辦法入庫(kù)。有沒(méi)有辦法插入其它9條?當(dāng)然在插入之間做查詢?nèi)ブ卦俨迦胧寝k法,但有沒(méi)有辦法讓PG自己完成?

回答
編輯回答
避風(fēng)港
  1. 使用存儲(chǔ)過(guò)程生成不一樣的時(shí)間。比如
CREATE OR REPLACE FUNCTION get_random_date(start_date date, end_date date) RETURNS integer AS  
$BODY$  
DECLARE  
    interval_days integer;  
    random_days integer;  
    random_date date;  
BEGIN  
    interval_days := end_date - start_date;  
    random_days := get_random_number(0, interval_days);  
    random_date := start_date + random_days;  
    RETURN date_part('year', random_date) * 10000 + date_part('month', random_date) * 100 + date_part('day', random_date);  
END;
  1. 把不希望重復(fù)的字段設(shè)成唯一索引。然后使用insert into ... on duplicate key update ...
INSERT INTO table(column1, column2) VALUES(value1,value2) ON DUPLICATE KEY UPDATE column2 = VALUES(column2);
2017年9月21日 03:48
編輯回答
尐飯團(tuán)

1)關(guān)于時(shí)間

PostgreSQL 提供一系列的函數(shù)獲取“當(dāng)前”時(shí)間。
a) 當(dāng)前事務(wù)啟動(dòng)的時(shí)間:transaction_timestamp()
b)當(dāng)前語(yǔ)句啟動(dòng)的時(shí)間:statement_timestamp()
c) 當(dāng)前函數(shù)被調(diào)用的時(shí)間:clock_timestamp()

使用 clock_timestamp() 即可。

https://www.postgresql.org/do...

2)關(guān)于插入時(shí)沖突

Insert 語(yǔ)句可以指定ON CONFLICT子句,用于定義插入數(shù)據(jù)沖突時(shí)的解決方式:

a) DO NOTHING: 不插入沖突數(shù)據(jù)
b) DO UPDATE: 沖突時(shí)修改原有記錄為給定值

https://www.postgresql.org/do...

2017年2月8日 01:54