Postgres将列值转换为查询中的模式前缀

时间:2017-04-25 13:22:09

标签: postgresql

我有一个数据库,它使用postgresql模式用于多租户目的。它在public架构中有一个名为customers的架构,其中包含idtenant列。租户的值是一个字符串,并且有一个相应的postgresql架构,其中包含匹配的表。

看起来像这样:

# public.customers  # first.users    # second.users
| id | tenant |     | id | name   |  | id | name   |
|----|--------|     |----|--------|  |----|--------|
| 1  | first  |     | 1  | bob    |  | 1  | jen    |
| 2  | second |     | 2  | jess   |  | 2  | mike   |

我想知道如何通过一个客户ID来创建单个查询来从模式中的表中获取值。

因此,如果我的customer_id为1,那么我在单个查询中如何select * from first.users

我猜这可能必须是用pgpsql编写的函数,但我没有很多经验。类似的东西:

select * from tenant_table(1, 'users');

2 个答案:

答案 0 :(得分:0)

单个查询无法做到这一点。

您必须使用一个选择模式名称的查询,然后构建第二个查询并运行它。

当然,您可以定义一个PL / pgSQL函数,它既可以为您执行,也可以使用EXECUTE执行动态查询。

答案 1 :(得分:0)

create or replace function f(_id int)
returns table (id int, name text) as $f$
declare _tenant text;
begin;

    select tenant into _tenant
    from public.customers
    where id = _id;

    return query execute format($e$
        select *
        from %I.users
    $e$, _tenant);
end;

$f$ language plpgsql;