2009-12-04 36 views

Trả lời

34

SQLalchemy không xây dựng cấu trúc này cho bạn. Bạn có thể sử dụng truy vấn từ văn bản.

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

EDIT:

Hơn một năm sau đó, nhưng bây giờ trên 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 

Tạo:

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

Một EDIT khác:

Bây giờ, 4 năm sau, cú pháp được kết hợp trong SQLAlchemy 0.9 và được chuyển thành 0.8.3; Bạn có thể tạo ra bất kỳ select() và sau đó sử dụng phương pháp mới from_select() của Insert đối tượng:

>>> 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

Bạn có đề xuất session.execute ('INSERT INTO t1 (% s)'% str (sqlalchemy_select_expression)) không? – joeforker

+0

Chắc chắn, tại sao không - không cần 'str()' mặc dù, vì '% s' đã làm điều đó. – nosklo

+0

Bây giờ vẫn không thể thực hiện được? – Hadrien

0

Như Noslko chỉ ra trong bình luận, bạn bây giờ có thể thoát khỏi sql liệu: 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 

Tạo:

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

Bây giờ bạn không phải tạo khoản riêng của mình. Bạn có thể sử dụng phương thức 'Insert.from_select' mới! Xem câu trả lời của tôi. – nosklo

13

Tính đến 0,8. 3, bây giờ bạn có thể làm điều này trực tiếp trong 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

Cảm ơn. Tôi sẽ thêm nó vào câu trả lời gốc. – nosklo

Các vấn đề liên quan