我正在从日志文件中将记录批量插入到数据库中.偶尔(每千行中约有1行)其中一行违反主键并导致事务失败.目前,用户必须手动浏览导致失败的文件,并在尝试重新导入之前删除有问题的行.鉴于要导入数百个这样的文件,这是不切实际的.
我的问题:如何跳过违反主键约束的记录插入,而不必SELECT在每行之前做一个声明,看它是否已经存在?
注意:我知道非常相似的问题#1054695,但它似乎是SQL Server特定的答案,我使用的是PostgreSQL(通过Python/psycopg2导入).
我有一个查询,可以插入给定数量的测试记录。看起来像这样:
CREATE OR REPLACE FUNCTION _miscRandomizer(vNumberOfRecords int)
RETURNS void AS $$
declare
-- declare all the variables that will be used
begin
select into vTotalRecords count(*) from tbluser;
vIndexMain := vTotalRecords;
loop
exit when vIndexMain >= vNumberOfRecords + vTotalRecords;
-- set some other variables that will be used for the insert
-- insert record with these variables in tblUser
-- insert records in some other tables
-- run another function that calculates and saves some stats regarding inserted records
vIndexMain …Run Code Online (Sandbox Code Playgroud) 我在PostgreSQL中有如下查询:
UPDATE
queue
SET
queue.status = 'PROCESSING'
WHERE
queue.status = 'WAITING' AND
queue.id = (SELECT id FROM queue WHERE STATUS = 'WAITING' LIMIT 1 )
RETURNING
queue.id
Run Code Online (Sandbox Code Playgroud)
并且许多工人尝试一次处理一项工作(这就是为什么我有限制1的子查询).在此更新之后,每个工作人员都会获取有关id的信息并处理工作,但有时他们会抓取相同的工作并处理两次或更多次.隔离级别为Read Committed.
我的问题是如何保证一件作品要处理一次?我知道那里有很多帖子,但我可以说我已经尝试了大部分帖子但它没有帮助();
AND pg_try_advisory_xact_lock(queue.id)外部查询的WHERE子句,但是...... [?]任何帮助,将不胜感激.
postgresql ×3
concurrency ×1
constraints ×1
database ×1
loops ×1
memory ×1
sql ×1
transactions ×1