简体   繁体   English

使用INTERSECT和UNNEST的sqlalchemy

[英]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通过应用labelINTERSECT查询放入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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM