1

这个问题与以下问题有关:

如何在 SQLAlchemy 中插入到 t1 (SELECT * FROM t2)?

但我想指定插入应该在哪些列上工作。也就是说,我希望 sqlalchemy 生成一个相当于

INSERT INTO t1 (col1, col2, col3) SELECT x,y,z FROM t2

我查看了编译文档,但我不清楚如何修改示例以指定列名。

4

1 回答 1

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
于 2013-03-05T17:27:25.727 回答