2009-12-04 36 views

回答

34

SQLalchemy不會爲您構建此構造。您可以使用來自文本的查詢。

session.execute('INSERT INTO t1 (SELECT * FROM t2)') 

編輯:

一年多過去了,但現在對SQLAlchemy的0.6+ you can create it

from sqlalchemy.ext import compiler 
from sqlalchemy.sql.expression import Executable, ClauseElement 

class InsertFromSelect(Executable, ClauseElement): 
    def __init__(self, table, select): 
     self.table = table 
     self.select = select 

@compiler.compiles(InsertFromSelect) 
def visit_insert_from_select(element, compiler, **kw): 
    return "INSERT INTO %s (%s)" % (
     compiler.process(element.table, asfrom=True), 
     compiler.process(element.select) 
    ) 

insert = InsertFromSelect(t1, select([t1]).where(t1.c.x>5)) 
print insert 

產地:

"INSERT INTO mytable (SELECT mytable.x, mytable.y, mytable.z FROM mytable WHERE mytable.x > :x_1)" 

另一個編輯:

現在,4年後,語法被納入SQLAlchemy 0.9,並backported到0.8.3;您可以創建任意select()然後用Insert對象的新from_select()方法:

>>> from sqlalchemy.sql import table, column 
>>> t1 = table('t1', column('a'), column('b')) 
>>> t2 = table('t2', column('x'), column('y')) 
>>> print(t1.insert().from_select(['a', 'b'], t2.select().where(t2.c.y == 5))) 
INSERT INTO t1 (a, b) SELECT t2.x, t2.y 
FROM t2 
WHERE t2.y = :y_1 

More information in the docs

+0

您會建議session.execute( 'INSERT INTO T1(%S)' %STR(sqlalchemy_select_expression))? – joeforker

+0

當然,爲什麼不 - 不需要'str()',因爲'%s'已經這樣做了。 – nosklo

+0

現在還不行嗎? – Hadrien

0

由於Noslko在評論中指出,現在你可以擺脫原始的SQL的: http://www.sqlalchemy.org/docs/core/compiler.html#compiling-sub-elements-of-a-custom-expression-construct

from sqlalchemy.ext.compiler import compiles 
from sqlalchemy.sql.expression import Executable, ClauseElement 

class InsertFromSelect(Executable, ClauseElement): 
    def __init__(self, table, select): 
     self.table = table 
     self.select = select 

@compiles(InsertFromSelect) 
def visit_insert_from_select(element, compiler, **kw): 
    return "INSERT INTO %s (%s)" % (
     compiler.process(element.table, asfrom=True), 
     compiler.process(element.select) 
    ) 

insert = InsertFromSelect(t1, select([t1]).where(t1.c.x>5)) 
print insert 

產地:

INSERT INTO mytable (SELECT mytable.x, mytable.y, mytable.z FROM mytable WHERE mytable.x > :x_1) 
+1

現在您不必創建自己的ClauseElement。你可以使用新的'Insert.from_select'方法!看到我的答案。 – nosklo

13

由於0.8。 3,您現在可以直接在sqlalchemy中執行此操作:Insert.from_select

sel = select([table1.c.a, table1.c.b]).where(table1.c.c > 5) 
ins = table2.insert().from_select(['a', 'b'], sel) 
+1

謝謝。我會將其添加到原始答案中。 – nosklo

相關問題