【问题标题】:Error: relation tbl does not exist postgres错误:关系 tbl 不存在 postgres
【发布时间】:2022-03-29 15:13:49
【问题描述】:

我在 PostgreSQL 中编写了一个 SQL 函数,可以访问另一个表中的数据。在运行该功能时,我收到以下错误

relation table2 does not exist postgres

这是我正在创建的功能

CREATE OR REPLACE FUNCTION func(tbl1 table1)
RETURNS TABLE(a int, b text, c int, d text) AS $$
    SELECT a, b, c, d
    FROM table2
    WHERE id = tbl1.user_id;
$$ 
language sql stable;

以防万一我将 table2 更改为 myschema.table2

我该怎么办?我不想将架构添加到查询中。我希望它采用函数所在的任何模式。

【问题讨论】:

  • 您是否检查过表 2 是否存在?
  • 是的。确实如此。已在编辑器中检查并运行
  • 在那种情况下,我得到了坚果。
  • 在执行对该函数的调用之前使用 SET search_path,或将其设为每个函数的固定设置

标签: sql postgresql function postgraphile


【解决方案1】:

模拟38.5.3。复合类型的 SQL 函数(https://www.postgresql.org/docs/current/xfunc-sql.html#XFUNC-SQL-FUNCTION-ARGUMENTS)

db fiddle

CREATE OR REPLACE FUNCTION func(table1)
RETURNS TABLE(a int, b text, c int, d text) AS $$
SELECT a, b, c, d FROM table2 WHERE id = $1.user_id;
$$
language sql;

叫它。 select (func(table1.*)).* from table1;

【讨论】:

  • 这不是我的问题的解决方案。我在函数中访问输入参数没有问题。我有这个错误:关系“table2”不存在”
  • 那么用户/角色可能无法访问该表。很可能是因为架构问题。
  • 表 2 指公众。表 2。 public 是您的默认搜索路径。那么 table2 与 myschema.table2 不同。是的,您可以设置 search_path 添加 myschema。但最好只使用 myshema.table2。
  • @VinitKhandelwal SET search_path TO myschema, public; 更好的是完整参考 myschema.table2。很奇怪,你查询数据跨表....
  • 那行得通。我在属性中设置
猜你喜欢
  • 2016-07-05
  • 2021-04-14
  • 1970-01-01
  • 2011-07-23
  • 2020-12-14
  • 2019-08-02
  • 2020-04-09
  • 2018-12-02
  • 1970-01-01
相关资源
最近更新 更多