SQLAlchemy and empty IN clause

前端 未结 5 567
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-02 10:17

I found out that SQLAlchemy translates

db.query(...).filter(A.id.in_(ids))

into

SELECT ...
FROM a
WHERE a.id != a.id

5条回答
  •  一向
    一向 (楼主)
    2021-02-02 10:29

    Be aware what you are asking for:

    • Only if the value of A.id is comparable any comparison can actually succeed. The non-existing value is not comparable to anything, all comparisons will result in a non-existing value which in turn is evaluated as False. That is, if A.ID is NULL then A.ID == anything is False and A.ID != anything is also False: A.ID == A.ID || A.ID != A.ID is False if A.ID is NULL.
    • The IN-clause with an empty sequence asks if the value is part of the empty list. The non-existing value is part of no list, not even the empty one.
    • Hence what you are asking for is some variation of IS NOT NULL and something that is part of nothing. This is a condition that has to be checked for. The non-existing value is not something; only some value that is not NULL can not be be a member of the empty list...
    • As sqlalchemy is clever about the fact that this is probably not the way you want to express this condition, it gives a warning. You should probably drop the IN-clause if the sequence is empty.

    For a concrete example this sqlfiddle

    For a more philosophical approach see What is the nature of void

提交回复
热议问题