Sqlalchemy将WHERE子句复制到FROM

时间:2019-06-04 09:21:31

标签: python postgresql sqlalchemy

我向psql写了原始查询,但工作正常,但是当我在sqlalchemy中编写此查询时,我的WHERE子句复制到FROM子句。

select id from T1 where arr && array(select l.id from T1 as l where l.box && box '((0,0),(50,50))');

在此查询中,我从T1中获取所有ID,其中具有整数的数组与子查询的结果相交。

class T1():
    arr = Column(ARRAY(Integer))
    ...

class T2():
    box = Column(Box)  # my geometry type
    ...

1个版本:

layers_q = select([T2.id]).where(T2.box.op('&&')(box))  # try find all T2 intersects with box
chunks = select([T1.id]).where(T1.arr.overlap(layers_q))  # try find all T1.id where T1.arr overlap with result from first query 


SELECT T1.id 
FROM T1 
WHERE T1.arr && (SELECT T2.id 
FROM T2 
WHERE T2.box && %(box_1)s)

这是关于类型转换的PG错误。我了解。

2版:

layers_q = select([T2.id]).where(T2.box.op('&&')(box))
chunks = select([T1.id]).where(T1.arr.overlap(func.array(layers_q)))

我添加了 func.array()以便转换为数组,但结果不正确:

SELECT T1.id 
FROM T1, (SELECT T2.id AS id 
FROM T2 
WHERE T2.box && %(box_1)s) 
WHERE T1.arr && array((SELECT T2.id 
FROM T2 
WHERE T2.box && %(box_1)s))

您可以在FROM子句中看到重复的内容。怎么正确?

1 个答案:

答案 0 :(得分:1)

我找到了解决方法!

func.array(select([T2.id]).where(T2.box.op('&&')(box)).as_scalar())

添加 as_scalar()都很好之后,因为在我的选择中,所有需要的ID都放在一个数组中。