我有一个临时表,大约有100万个条目。临时表存储较大查询的结果。例如,我想一次处理1000个这些记录。设置查询的最佳方法是什么,以便获得前1000行,然后是下一行1000,等等?它们本身并不是有序的,但是临时表只有一个带有ID的列,所以我可以在必要时订购它。我正在考虑使用临时表创建一个额外的列来对所有行进行编号,例如:
CREATE TEMP TABLE tmptmp AS
SELECT ##autonumber somehow##, id
FROM .... --complicated query
然后我可以做到:
SELECT * FROM tmptmp WHERE autonumber>=0 AND autonumber < 1000
等等......我将如何实现这一目标?或者,还有更好的方法?我正在使用Python和PostgreSQL。
答案 0 :(得分:4)
使用游标并获取所需的行。当你拥有大量记录时,偏移...限制会变慢,光标会做得更好。
http://www.postgresql.org/docs/8.4/interactive/sql-fetch.html
答案 1 :(得分:1)
也许你可以使用这样的东西(我们在批量更新一个包含+20万行的表并且不想占用复制时使用)。
import sys
import psycopg2
from datetime import datetime
firstid = 0
splitsize = 50 # Size of each batch
# Complicated query
query_complex = """
CREATE TEMP TABLE tmptmp AS
SELECT * FROM schema.massive_table
"""
# Query to be run at intervals
query = """
SELECT * FROM tmptmp WHERE id BETWEEN %(startid)s AND %(endid)s
"""
conn = psycopg2.connect("dbname=database_name user=postgres")
curs = conn.cursor()
# Run complicated query
curs.execute(query_complex)
# Get highest id
curs.execute("SELECT max(id) FROM tmptmp")
maxid = curs.fetchall()[0][0]
print "Max id: %s" % maxid
for startid in range(firstid, maxid, splitsize):
endid = startid + splitsize - 1
print "%s: Running query on range %s to %s" % (datetime.now(), startid, endid)
curs.execute(query, {'startid':startid, 'endid':endid})
print "%s: Affected rows: %s. Total completed: %s%%" % (datetime.now(), curs.rowcount, round((endid * 100) / maxid, 3))
print "Done."
以下输出:
Max id: 308
2010-06-18 11:59:11.271000: Running query on range 0 to 49
2010-06-18 11:59:11.271000: Affected rows: 49. Total completed: 15.0%
2010-06-18 11:59:11.271000: Running query on range 50 to 99
2010-06-18 11:59:11.271000: Affected rows: 50. Total completed: 32.0%
2010-06-18 11:59:11.271000: Running query on range 100 to 149
2010-06-18 11:59:11.271000: Affected rows: 50. Total completed: 48.0%
2010-06-18 11:59:11.271000: Running query on range 150 to 199
2010-06-18 11:59:11.271000: Affected rows: 49. Total completed: 64.0%
2010-06-18 11:59:11.271000: Running query on range 200 to 249
2010-06-18 11:59:11.271000: Affected rows: 42. Total completed: 80.0%
2010-06-18 11:59:11.271000: Running query on range 250 to 299
2010-06-18 11:59:11.318000: Affected rows: 3. Total completed: 97.0%
2010-06-18 11:59:11.318000: Running query on range 300 to 349
2010-06-18 11:59:11.318000: Affected rows: 1. Total completed: 113.0%
Done.
//约翰