2009-12-04 4 views

답변

34

SQLalchemy는이 구문을 작성하지 않습니다. 텍스트의 쿼리를 사용할 수 있습니다.

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

편집 :

이상 1 년 후,하지만 지금은 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에 구문이 통합되고 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합니다. Noslko 코멘트에서 지적

+0

session.execute ('T1 INTO INSERT (% s의)'% str을 (sqlalchemy_select_expression))? – joeforker

+0

물론, 왜 '% s'이 이미 그렇게했기 때문에'str()'이 필요하지는 않습니다. – nosklo

+0

지금도 여전히 실행 가능하지 않습니까? – Hadrien

0

, 당신은 지금 원시 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

관련 문제