PostgreSQL dynamic table access

回眸只為那壹抹淺笑 提交于 2019-12-11 03:37:03

问题


I have a products schema and some tables there.
Each table in products schema has an id, and by this id I can get this table name, e.g.

products
    \ product1
    \ product2
    \ product3

I need to select info from dynamic access to appropriate product, e.g.

SELECT * FROM 'products.'(SELECT id from categories WHERE id = 7);

Of course, this doesn't work...
How I can do something like that in PostgreSQL?


回答1:


OK, I found a solution:

CREATE OR REPLACE FUNCTION getProductById(cid int) RETURNS RECORD AS $$
    DECLARE
    result RECORD;

    BEGIN
        EXECUTE 'SELECT * FROM ' || (SELECT ('products.' || (select category_name from category where category_id = cid) || '_view')::regclass) INTO result;

        RETURN result;
    END;
$$ LANGUAGE plpgsql;

and to select:

SELECT * FROM getProductById(7) AS b (category_id int, ... );

works for PostgreSQL 9.x




回答2:


If you can change your database layout to use partitioning instead, that would probably be the way to go. Then you can just access the "master" table as if it were one table rather than multiple subtables.

You could create a view that combines the tables with an extra column corresponding to the table it's from. If all your queries specify a value for this extra column, the planner should be smart enough to skip scanning all the rest of the tables.

Or you could write a function in PL/pgSQL, using the EXECUTE command to construct the appropriate query after fetching the table name. The function can even return a set so it can be used in the FROM clause just as you would a table reference. Or you could just do the same query construction in your application logic.




回答3:


To me, it sounds like you've a major schema design problem: shouldn't you only have one products table with a category_id in it?

Might you be maintaining the website mentioned in this article?

http://thedailywtf.com/Articles/Confessions-The-Shopping-Cart.aspx



来源:https://stackoverflow.com/questions/5772699/postgresql-dynamic-table-access

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