How to join a table with dynamic id in postgres?

I have a table name tablecontaining two columns foreign_table_nameand foreign_key.

Is it possible to write a query SELECTthat will have the values ​​of JOINthis table, and a table whose name is listed in the column foreign_table_name?

For example, if we know that all possible target external tables have a field name, I would like to know if I can write something that:

SELECT table.foo, table.bar, foreign_table.name 
FROM table
  JOIN $foreign_table AS foreign_table 
       ON (foreign_table.id = table.foreign_key
           $foreign_table = table.foreign_table);

Any decision using PlpgSQL is, of course, accepted.

Here is the simple content:

Table ``table``
------------------------------------------------
| foo | bar | foreign_table_name | foreign_key |
------------------------------------------------
|  A  |  1  | fruits             | 8           |
|  B  |  2  | vegetable          | 5           |
------------------------------------------------

Table ``fruit``
---------------
| id  | name  |
---------------
| 8   | apple |
---------------

Table ``vegetable``
----------------
| id  | name   |
----------------
| 5   | carrot |
----------------

Expected Results Table:

----------------------
| foo | bar | name   |
----------------------
|  A  |  1  | apple  |
|  B  |  2  | carrot |
----------------------

EDIT: I added an example of a complete table, trying to be more clear.

+4
source share
1 answer

, , , PL/PgSQL, .

CREATE OR REPLACE FUNCTION dynamic_call(tblname text)
RETURNS TABLE (foo int, bar text, fname text)
AS $$
BEGIN
  RETURN QUERY EXECUTE format('
    SELECT t.foo, table.bar, f."name"
    FROM mytable t
    JOIN %I AS f ON (f.id = t.foreign_key);', tblname);
END;
$$ LANGUAGE plpgsql;

. PL/PgSQL.

+6

Source: https://habr.com/ru/post/1525733/


All Articles