简体   繁体   English

从游标创建临时表

[英]create temporary table from cursor

Is there any way, in PostgreSQL accessed from Python using SQLObject, to create a temporary table from the results of a cursor? 在使用SQLObject从Python访问的PostgreSQL中,是否可以通过游标的结果创建临时表?

Previously, I had a query, and I created the temporary table directly from the query. 以前,我有一个查询,我直接从查询中创建了临时表。 I then had many other queries interacting w/ that temporary table. 然后,我有许多其他查询与该临时表进行交互。

Now I have much more data, so I want to only process 1000 rows at a time or so. 现在我有更多的数据,所以我一次只想处理1000行。 However, I can't do CREATE TEMP TABLE ... AS ... from a cursor, not as far as I can see. 但是,我无法从游标执行CREATE TEMP TABLE ... AS ... ,就我所知。 Is the only thing to do something like: 是唯一要做的事情:

rows = cur.fetchmany(1000);
cur2 = conn.cursor()
cur2.execute("""CREATE TEMP TABLE foobar (id INTEGER)""")
for row in rows:
    cur2.execute("""INSERT INTO foobar (%d)""" % row)

or is there a better way? 或者,还有更好的方法? This seems awfully inefficient. 这似乎效率很低。

Well Postgres is reading the cursor record by record and you're just getting 1000 of those with the fetchmany call and loading them into memory. 好了,Postgres正在逐条记录地读取游标记录,而通过fetchmany调用就可以获取其中的1000条记录并将其加载到内存中。 I'm not sure how you would really expect what you're asking to work. 我不确定您会如何期望自己的工作。

A better performing version of that would make sure that all those INSERTS were wrapped in a single BEGIN and END so that its one transaction. 更好地执行该操作的版本将确保将所有这些INSERTS包裹在单个BEGIN和END中,以便进行一次事务处理。

Is there a reason for the cursor as opposed to just adding a column via row_number() into a temporary table to start off with - so that its ordered? 游标有什么理由,而不是仅仅通过row_number()将一列添加到临时表中以开始-以便其有序?

I haven't used PostgreSQL but I know that to insert the results of a stored procedure you would do: 我没有使用PostgreSQL,但是我知道要插入存储过程的结果,您可以这样做:

INSERT INTO #SHIPINFO
exec TESTDTA.S59RSH05 @SCBILLTO, @INID, @ADRSTYPE

Taken from here . 取自这里

So could you maybe do something similar. 所以您也许可以做类似的事情。 Maybe send it the cursor results as a whole so something like: 也许将光标结果作为一个整体发送给它,例如:

CREATE TEMP TABLE foobar (id INTEGER)
INSERT INTO foobar 'rows'

I ended up doing this: 我最终这样做:

        sql.execute(connection, """
INSERT INTO blah VALUES %s;""" % (
    ", ".join("(%d)" % hid for hid in hids)))

instead of 1000 separate inserts. 而不是1000个单独的插件。 Still don't know a better way, but this works well enough. 仍然不知道更好的方法,但是效果很好。

You might try 你可以试试

from psycopg2.extras import execute_values
execute_values(cursor, "INSERT INTO temp (id) VALUES %s", hids)

see the Fast execution helpers docs for full dets 有关完整的说明,请参见快速执行帮助器文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM