du1843 2009-05-18 12:12
浏览 99
已采纳

PostgreSQL:每年创建新/重复现有表的最佳方式

referring to this question, I've decided to duplicate the tables every year, creating tables with the data of the year, something like, for example:

orders_2008
orders_2009
orders_2010
etc...

Well, I know that probably the speed problem could be solved with just 2 tables for each element, like orders_history and order_actual, but I thought that once the handler code is been wrote, there will be no difference.. just many tables.

Those tables will have even some child with foreign key; for example the orders_2008 will have the child items_2008:

CREATE TABLE orders_2008 (
    id serial NOT NULL,
    code character(5),
    customer text
);

ALTER TABLE ONLY orders_2008
    ADD CONSTRAINT orders_2008_pkey PRIMARY KEY (id);

CREATE TABLE items_2008 (
    id serial NOT NULL,
    order_id integer,
    item_name text,
    price money
);

ALTER TABLE ONLY items_2008
    ADD CONSTRAINT items_2008_pkey PRIMARY KEY (id);

ALTER TABLE ONLY items_2008
    ADD CONSTRAINT "$1" FOREIGN KEY (order_id) REFERENCES orders_2008(id) ON DELETE CASCADE;

So, my problem is: what do you think is the best way to replicate those tables every 1st january and, of course, keeping the table dependencies?

A PHP/Python script that, query after query, rebuild the structure for the new year (called by a cron job)? Can the PostgreSQL's functions be used in that way? If yes, how (an little example will be nice)

Actually I'm going for the first way (a .sql file containing the structure, and a php/python script loaded by cronjob that rebuild the structure), but i'm wondering if this is the best way.

edit: i've seen that the pgsql function CREATE TABLE LIKE, but the foreigns keys must be added in a second time.. or it will keep the new tables referencied tot he old one.

  • 写回答

5条回答 默认 最新

  • dss524049 2009-05-18 12:18
    关注

    PostgreSQL has a feature that lets you create a table that inherits fields from another table. The documentation can be found in their manual. That might simplify your process a bit.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器