SQL 炼金术中的切片过滤条件
Slicing filter criteria in SQL alchemy
我有一个带有过滤条件的查询,我想根据第 3 行的片段进行检查。HouseReport.location 可以包含字符和数字。查询看起来像这样。
query = dbsession.query(HouseReport).filter(
HouseReport.ID == loan.loan_id,
HouseReport.location[:1].notin_(('8', '9'))
)
有没有办法检查过滤条件的一部分是否不在第 3 行中看到的 8 或 9 中?谢谢。
由于您只是比较第一个字符,因此有多种实现方法。
选项-1: startswith(...)
...
filter(or_(
HouseReport.location.startswith('8'),
HouseReport.location.startswith('9'),
))
Option-2: SUBSTRING 函数
这是特定于数据库的,可能需要根据底层数据库以不同方式实施。但是 SA 似乎为大多数数据库实现了这一点(尽管没有记录)。有关详细信息,请参阅 。
...
filter(~func.substring(HouseReport.location, 1, 1).in_(('8', '9')))
我有一个带有过滤条件的查询,我想根据第 3 行的片段进行检查。HouseReport.location 可以包含字符和数字。查询看起来像这样。
query = dbsession.query(HouseReport).filter(
HouseReport.ID == loan.loan_id,
HouseReport.location[:1].notin_(('8', '9'))
)
有没有办法检查过滤条件的一部分是否不在第 3 行中看到的 8 或 9 中?谢谢。
由于您只是比较第一个字符,因此有多种实现方法。
选项-1: startswith(...)
...
filter(or_(
HouseReport.location.startswith('8'),
HouseReport.location.startswith('9'),
))
Option-2: SUBSTRING 函数
这是特定于数据库的,可能需要根据底层数据库以不同方式实施。但是 SA 似乎为大多数数据库实现了这一点(尽管没有记录)。有关详细信息,请参阅
...
filter(~func.substring(HouseReport.location, 1, 1).in_(('8', '9')))