2009-12-04 8 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 साल बाद, सिंटैक्स को एसक्लाक्लेमी 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

+0

सुझाव चाहेंगे session.execute ('t1 में डालने (% s)'% str (sqlalchemy_select_expression))? – joeforker

+0

निश्चित रूप से, क्यों नहीं - 'str()' की आवश्यकता नहीं है, क्योंकि '% s' पहले से ही ऐसा करता है। – nosklo

+0

क्या यह अभी भी करने योग्य नहीं है? – Hadrien

0

रूप Noslko टिप्पणी में बताया, तो आप अब कच्चे एसक्यूएल से छुटकारा प्राप्त कर सकते हैं: 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

अब आपको अपना खुद का क्लॉज एलिमेंट बनाना नहीं है। आप नई '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

संबंधित मुद्दे