SQLAlchemy 中的 VALUES 子句 [英] VALUES clause in SQLAlchemy
本文介绍了SQLAlchemy 中的 VALUES 子句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法在 SQLAlchemy 中构建一个 Query
对象,它相当于:
Is there a way to build a Query
object in SQLAlchemy which will be the equivalent of:
SELECT * FROM (VALUES (1, 2, 3)) AS sq;
从我在文档中看到的内容来看,VALUES
子句仅与 INSERT
一起使用.
From what I see in the documentation, the VALUES
clause appears only in use with INSERT
.
推荐答案
插入中的VALUES"是标准 SQL,独立的VALUES"关键字是 Postgresql 的东西.在 PGValues 上有一个快速编译器配方(复制到这里以防我更改维基有一天):
well "VALUES" in an insert is the standard SQL, the standalone "VALUES" keyword is a Postgresql thing. There's a quick compiler recipe for this one at PGValues (copied here in case I change the wiki someday):
from sqlalchemy import *
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.sql.expression import FromClause
from sqlalchemy.sql import table, column
class values(FromClause):
def __init__(self, *args):
self.list = args
def _populate_column_collection(self):
self._columns.update(
[("column%d" % i, column("column%d" % i))
for i in xrange(1, len(self.list[0]) + 1)]
)
@compiles(values)
def compile_values(element, compiler, asfrom=False, **kw):
v = "VALUES %s" % ", ".join(
"(%s)" % ", ".join(compiler.render_literal_value(elem, None) for elem in tup)
for tup in element.list
)
if asfrom:
v = "(%s)" % v
return v
if __name__ == '__main__':
t1 = table('t1', column('a'), column('b'))
t2 = values((1, 0.5), (2, -0.5)).alias('weights')
print select([t1, t2]).select_from(t1.join(t2, t1.c.a==t2.c.column2))
这篇关于SQLAlchemy 中的 VALUES 子句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文