Sqlalchemy duplicated WHERE clause to FROM

本秂侑毒 提交于 2021-02-17 03:40:17

问题


I wrote raw query to psql and it's work fine but when i wrote this in sqlalchemy my WHERE clause duplicated to FROM clause.

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

In this query i fetch all id from T1 where array with ints intersects with results from subquery.

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

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

1 verison:

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)

This i have a PG error about type cast. I understand it.

2 version:

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

I added func.array() for cast to array but result is not correct:

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))

There you can see what i have duplicate in FROM clause. How did it correctly?


回答1:


I find solution!

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

After added as_scalar() all be good, beacause in my select all ids need have in one array.



来源:https://stackoverflow.com/questions/56441019/sqlalchemy-duplicated-where-clause-to-from

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!