سؤال

Given a table called namespace_list with an INTEGER[] column called namespace_ids.

I have the following query:

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

which I am executing as:

cur.execute(query, data)

and where data is:

data = ([1, 2], 1)

I am getting the following error:

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.

Why is this not working? Looking at http://www.postgresql.org/message-id/CAG7mmoxZdRdatjWSYLBCVGJ4CPMa38ARSZByWe9xrWHKP0mB1g@mail.gmail.com, and other tutorials on Postgres Arrays, it seems that I have the correct query.

I am following what http://initd.org/psycopg/docs/usage.html#adapt-list has as an example as well. Is there anything wrong with my query, or the way I am using arrays with psycopg2?

هل كانت مفيدة؟

المحلول

The problem is that the SQL expression:

<column> = ANY(<array>)

returns true if the scalar value in <column> is equal to any value in <array> comparing the values one by one. But your column is not a scalar value, it is an array and that's why PostgreSQL says:

operator does not exist: integer[] = integer

An operator to compare an array (left) to any integer (right) doesn't exists. To fix this you can use an intersection operator (&&) (if you need to match just one id from both sets) or the equality operator (=) if you want to match all array elements:

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

The trick here is that psycopg converts Python lists to literal arrays (ARRAY[...]) that you can use anywhere you would use them in standard SQL.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top