简体   繁体   中英

Why this query doesn't work (problem with EXISTS)

I'm struggling with such query (generated by sqlalchemy. I've renamed it for clarity)

SELECT table.x + :dx AS cx, table.y + :dy AS cy 
FROM table
WHERE NOT (EXISTS (SELECT * FROM table AS table_1
                   WHERE table_1.x = cx AND table_1.y = cy))
  AND     (EXISTS (SELECT * FROM table2
                   WHERE table2.table_id = table.id))

For dx, dy = 1, 1 and tables:

 Table:
  id | x | y
 ----+---+---
   1 | 0 | 0

 Table2:
  id | table_id
 ----+----------
  1  | 1

It should return:

  cx | cy
 ----+----
   1 |  1

However the second condition seems to return false.

EDIT: It seems to be a problem with transaction flushing in SQLAlchemy. I thought that in case of executing query (non-ORM mapped) it will automatically flush. However it seems that it is not flushed in such case or flushed in incorrect order. In any case adding additional model.DBSession.flush() seems to fixed the problem.

As written in edit the problem was in flushing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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