[英]sqlalchemy using INTERSECT and UNNEST
I'm trying to translate a raw SQL to sqlalchemy core/orm but I'm having some difficulties. 我正在尝试将原始SQL转换为sqlalchemy core / orm,但遇到了一些困难。 Here is the SQL:
这是SQL:
SELECT
(SELECT UNNEST(MyTable.my_array_column)
INTERSECT
SELECT UNNEST(ARRAY['VAL1', 'VAL2']::varchar[])) AS matched
FROM
MyTable
WHERE
my_array_column && ARRAY['VAL1', 'VAL2']::varchar[];
The following query, gives me a FROM
clause which I don't need in my nested SELECT
: 以下查询为我提供了
FROM
子句,该子句在嵌套SELECT
不需要的:
matched = select([func.unnest(MyTable.my_array_column)]).intersect(select([func.unnest('VAL1', 'VAL2')]))
# SELECT unnest(MyTable.my_array_colum) AS unnest_1
# FROM MyTable INTERSECT SELECT unnest(%(unnest_3)s, %(unnest_4)s) AS unnest_2
How can I tell the select
to not include the FROM
clause? 如何告诉
select
不包含FROM
子句? Note that func.unnest()
only accepts a column. 请注意
func.unnest()
仅接受一列。 So I cannot use func.unnest('my_array_column')
. 所以我不能使用
func.unnest('my_array_column')
。
Referring to a table of an enclosing query in a subquery is the process of correlation , which SQLAlchemy attempts to do automatically. 在子查询中引用封闭查询的表是关联过程,SQLAlchemy会尝试自动执行此过程。 In this case, it doesn't quite work, I believe, because your
INTERSECT
query is a "selectable", not a scalar value, which SQLAlchemy attempts to put in the FROM
list instead of the SELECT
list. 我相信,在这种情况下,它不太有效,因为您的
INTERSECT
查询是“可选的”而不是标量值,SQLAlchemy试图将其放入FROM
列表而不是SELECT
列表中。
The solution is twofold. 解决方案是双重的。 We need to make SQLAlchemy put the
INTERSECT
query in the SELECT
list by applying a label
, and make it correlate MyTable
correctly: 我们需要使SQLAlchemy通过应用
label
将INTERSECT
查询放入SELECT
列表中,并使其正确关联MyTable
:
select([
select([func.unnest(MyTable.my_array_column)]).correlate(MyTable)
.intersect(select([func.unnest('VAL1', 'VAL2')]))
.label("matched")
]).select_from(MyTable)
# SELECT (SELECT unnest("MyTable".my_array_column) AS unnest_1 INTERSECT SELECT unnest(%(unnest_3)s, %(unnest_4)s) AS unnest_2) AS matched
# FROM "MyTable"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.