检查Postgres表中是否存在记录 [英] Check if records exists in a Postgres table

查看:1622
本文介绍了检查Postgres表中是否存在记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须每20秒读取一次CSV。每个CSV包含最小。最大500。 60000线。我必须在Postgres表中插入数据,但在此之前,我需要检查项目是否已经插入,因为有很高的概率获得重复项目。

I have to read a CSV every 20 seconds. Each CSV contains min. of 500 to max. 60000 lines. I have to insert the data in a Postgres table, but before that I need to check if the items have already been inserted, because there is a high probability of getting duplicate item. The field to check for uniqueness is also indexed.

因此,我读取chunks中的文件,并使用IN子句来获取数据库中已经存在的项目。

So, I read the file in chunks and use the IN clause to get the items already in the database.

有更好的方法吗?

推荐答案

这应该表现良好:

CREATE TEMP TABLE tmp AS SELECT * FROM tbl LIMIT 0 -- copy layout, but no data

COPY tmp FROM '/absolute/path/to/file' FORMAT csv;

INSERT INTO tbl
SELECT tmp.*
FROM   tmp
LEFT   JOIN tbl USING (tbl_id)
WHERE  tbl.tbl_id IS NULL;

DROP TABLE tmp; -- else dropped at end of session automatically

这个答案

这篇关于检查Postgres表中是否存在记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆