如果提供了空列表作为参数,我想将 IN 语句作为我的 sql 查询的可选部分,但未能提供。我可以做解决方法并在代码中使用一些默认值而不是空列表(所有 cam_ids),但我想知道如何正确地做到这一点。
我有以下 sql 表达式(实际表达式要长得多):
SELECT
id, cam_id
FROM sometable
WHERE id > %(_id)s
// if use = instead of IN, it works well (of course if cameras is just one value, not array)
AND (%(camera)s is NULL OR cam_id IN %(camera)s)
在 python 中,我通过以下方式为查询提供了参数:
values = {"_id": 10, camera: tuple(1, 2, 3)]}
curs.execute(query, values)
如果元组不为空,则一切正常,否则:
如果相机 = 无,我收到以下错误:
psycopg2.errors.SyntaxError:“NULL”处或附近的语法错误第 6 行:WHERE(NULL 为 NULL 或 cam_id IN NULL)
如果 camera = tuple(),我得到以下错误:
psycopg2.errors.SyntaxError:“)”处或附近的语法错误第 6 行:WHERE (() 为 NULL 或 cam_id IN ())
为了更清楚:
如果提供了空数组,我想获得所有可能的 cam_ids的所有结果,因此结果应该与SELECT * FROM tablename;
编辑:莫里斯·迈耶
我在尝试进行更大的查询时发现了以下问题
select * from vworker_tracks
where
// still need some default value: cam_id != ''
(cam_id = any('{}') or cam_id != '')
and
// unexpected results when both are true, provides all tracks > 0.0
(track_duration_seconds = 2.5 or track_duration_seconds > 0.0)
and
id < 100
order by id desc limit 10;