检查哪些 id 存在 postgrestable

check which ids exists postgrestable

快速检查 postgreSQL 中存在哪些 id table

我写了下面的函数,但是当 len(x) 大于 500 000

时速度很慢
import psycopg2
conn = psycopg2.connect(...)
cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)

def check_exist(lst):
    exist = []
    not_exist = []
    for i in lst:
        cursor.execute(f"SELECT * FROM table1 where id={i}")
        row = cursor.fetchone()
        if row:
            exist.append(i)
        else:
            not_exist.append(i)
    return exist, not_exist

x, y = check_exist(['2','4','3000','50000','10000000'])

您可以使用 IN 子句。使用您的 ID 创建一个列表。在您的应用程序中迭代列表以验证哪些 ID 没有出现在找到的记录列表中。

Select id from table1 where id IN ( [your list] )

一点:从table查询较少的字段可以使您的查询更有效率。

您可以使用 ANY 并让 Postgres 完成大部分工作:

import psycopg2, time
# database is in a datacenter just using a tunnel!
conn = psycopg2.connect("dbname=mf port=5959 host=localhost user=mf_usr")
cur = conn.cursor()

ids = [x for x in range(0, 750000)]

sql = """
    SELECT array_agg(id) from __users where id = ANY(%s);
"""
# array_agg: Postgres returns an array of ids!

_start = time.time()
cur.execute(sql, (ids, ))
existingIds = cur.fetchone()[0]
missingIds = set(ids) - set(existingIds)

print(len(existingIds))
print(len(missingIds))
print('Took: %.6f seconds' % (time.time() - _start))

输出:

284365
465635
Took: 5.564851 seconds

注意:确保在ID列上有一个索引