无法创建简单的Postgresql函数

时间:2014-01-21 02:45:26

标签: postgresql postgresql-9.2

我正在尝试在Postgresql中创建一个用户定义的函数:

CREATE FUNCTION get_balance(user_id integer, statuses integer[]) RETURNS INTEGER 
AS $$
select SUM(table1.credit)
from table1

inner join table2
on table2.field1 = table1.id

inner join table3
on table3.field1 = table2.id
where table3.status_id in (statuses); $$

LANGUAGE SQL;

错误是:

ERROR:  operator does not exist: integer = integer[]
LINE 11: where table3.status_id in (statuses); $$

我做错了什么?

1 个答案:

答案 0 :(得分:1)

此:

table3.status_id in (statuses)

可以简化为例子:

regress=>  SELECT 1 IN (ARRAY[1,2,3]);
ERROR:  operator does not exist: integer = integer[]
LINE 1: SELECT 1 IN (ARRAY[1,2,3]);
                 ^
HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.

...但IN需要一个文字列表,例如:

regress=> SELECT 1 IN (1, 2, 3);

由于你想传​​递一个数组,你需要使用需要数组输入的= ANY(...)

regress=> SELECT 1 = ANY (ARRAY[1,2,3]);
 ?column? 
----------
 t
(1 row)
相关问题