2017-04-25 114 views
0

我有一个使用postgresql模式进行多租户用途的数据库。它在名为customerspublic模式中有一个表,其中idtenant列。 tenant的值是一个字符串,并且有一个相应的postgresql模式,其中的表格匹配。Postgres在查询中将列值转换为模式前缀

它看起来像这样:

# 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'); 

+0

是否有关系之间的FK?.. –

+0

没有FK没有........ – brad

回答

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; 
0

你不能用单个查询来做到这一点。

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

当然,您可以定义一个PL/pgSQL函数来为您执行这两个操作,并使用EXECUTE执行动态查询。