How to join table with dynamic identifier in postgres?

不想你离开。 提交于 2019-12-04 23:36:43

问题


I have a table name table containing two columns foreign_table_name, and foreign_key.

Is it possible to write a SELECT query that would JOIN values of this table and the table which name is specified in the column foreign_table_name ?

For instance, if we know that all possible targetted foreign tables have a name field, I would like to know if I could write something that would:

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 solution using PlpgSQL is of course accepted.

Here's a 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 |
----------------

The expected result table would be:

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

EDIT: I added the full table example in an attempt to be clearer.


回答1:


It's usually way easier to do this sort of thing on the client side, but if you want it's possible with PL/PgSQL, e.g.

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;

For more information, see the PL/PgSQL documentation.



来源:https://stackoverflow.com/questions/21619189/how-to-join-table-with-dynamic-identifier-in-postgres

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!