Psycopg2“运算符不存在:整数[] =整数”错误

时间:2014-02-18 17:15:25

标签: python sql postgresql psycopg2

给定一个名为namespace_list的表格,其中INTEGER[]列名为namespace_ids

我有以下查询:

query = SELECT * FROM namespace_list WHERE namespace_ids = ANY(%s) 
and application_id=%s

我正在执行:

cur.execute(query, data)

以及数据的位置:

data = ([1, 2], 1)

我收到以下错误:

operator does not exist: integer[] = integer at character 50\nHINT:
No operator matches the given name and argument type(s).
You might need to add explicit type casts.

为什么这不起作用?查看http://www.postgresql.org/message-id/CAG7mmoxZdRdatjWSYLBCVGJ4CPMa38ARSZByWe9xrWHKP0mB1g@mail.gmail.com和Postgres Arrays上的其他教程,似乎我有正确的查询。

我也关注http://initd.org/psycopg/docs/usage.html#adapt-list的例子。我的查询或者我使用psycopg2的数组的方式有什么问题吗?

1 个答案:

答案 0 :(得分:2)

问题是SQL表达式:

<column> = ANY(<array>)
如果<column>中的标量值等于<array>中逐个比较值的任何值,则

返回true。但是你的列不是标量值,它是一个数组,这就是PostgreSQL说的原因:

operator does not exist: integer[] = integer

将数组(左)与任何整数(右)进行比较的运算符不存在。要解决此问题,您可以使用交集运算符(&&)(如果需要匹配两个集合中的一个id)或等值运算符(=),如果要匹配所有数组元素: / p>

SELECT * FROM namespace_list WHERE namespace_ids && %s and application_id=%s

这里的技巧是psycopg将Python列表转换为文字数组(ARRAY[...]),您可以在标准SQL中使用它们的任何地方使用它们。