1

この質問は、次の質問に関連しています。

SQLAlchemyでINSERTINTOt1(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 に答える