postgresql - 没有函数匹配,任何元素的错误都不明显

标签 postgresql

当尝试将下面的函数与 SELECT * FROM t WHERE checkrange(3,r) 一起使用时,返回错误“No function matches”

CREATE FUNCTION checkRange(
     p_val anyelement, p_range anyarray
) RETURNS boolean AS $f$
     SELECT bool_or(p_val <@ r) FROM unnest(p_range) t(r);
$f$ LANGUAGE SQL IMMUTABLE;

假设

CREATE TABLE t (id serial, r int4range[]); 
INSERT INTO t (r) VALUES 
  ('{"[2,5]","[100,200]"}'::int4range[]),
  ('{"[6,9]","[201,300]"}'::int4range[]);

PS:我记得我们需要对 PostgreSQL 的 anyelement 做一些变通,但不是什么...错误消息并不明显。

最佳答案

我认为这就是原因:

来自 https://www.postgresql.org/docs/current/static/extend-type-system.html#extend-types-polymorphic

Each position (either argument or return value) declared as anyelement is allowed to have any specific actual data type, but in any given call they must all be the same actual type. Each position declared as anyarray can have any array data type, but similarly they must all be the same type. And similarly, positions declared as anyrange must all be the same range type. Furthermore, if there are positions declared anyarray and others declared anyelement, the actual array type in the anyarray positions must be an array whose elements are the same type appearing in the anyelement positions.

这样就可以了:

select * from checkRange('[100,200]'::int4range, '{"[6,9]","[201,300]"}'::int4range[])

但那不会:

select * from checkRange(1, '{"[6,9]","[201,300]"}'::int4range[])

如果您希望您的函数使用这个 anyarray,只需将它的第一个定义为整数以保持多态参数绑定(bind):

CREATE FUNCTION checkRange(
     p_val bigint, p_range anyarray
) RETURNS boolean AS $f$
     SELECT bool_or(p_val <@ r) FROM unnest(p_range) t(r);
$f$ LANGUAGE SQL IMMUTABLE;

关于postgresql - 没有函数匹配,任何元素的错误都不明显,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46806592/

相关文章:

sql - PostgreSQL group by with interval 但没有窗口函数

sql - 在更新中使用 replace() 函数来更改一列的多个子字符串

sql - 如何将此 mysql 查询转换为 postgres 9.4

django - 使用 Heroku 的关系 django_migrations 的权限被拒绝

django - settings.DATABASES 配置不当

ruby-on-rails - 通过 2 个不同的关联模型进行 Rails 查询

SQL 查询连接两个表类似于左外连接

postgresql - Postgres 9.3 的 Docker 入口点

postgresql - Celery:使用 PostgreSQL 而不是 RabbitMQ

python - 在 Django 或数据库中在哪里检查约束?