此问题与以下问题有关:
How do I INSERT INTO t1 (SELECT * FROM t2) in SQLAlchemy?
但是我想指定插件应该在哪些列上工作。也就是说,我希望sqlalchemy生成一个等同于
的查询 INSERT INTO t1 (col1, col2, col3) SELECT x,y,z FROM t2
我查看了编译文档,但我不清楚如何修改example以便能够指定列名。
答案 0 :(得分:0)
以下修改可能有所帮助:
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.sql.expression import Executable, ClauseElement
class InsertFromSelect(Executable, ClauseElement):
def __init__(self, table, columns, select):
self.table = table
self.columns = columns
self.select = select
@compiles(InsertFromSelect)
def visit_insert_from_select(element, compiler, **kw):
return "INSERT INTO %s (%s) %s" % (
compiler.process(element.table, asfrom=True),
", ".join(element.columns), # @note: not a very safe/robust way to compose SQL
compiler.process(element.select)
)
insert = InsertFromSelect(
t1,
("col1", "col2", "col3",),
select([t2.c.x, t2.c.y, t2.c.z])
)
print insert