插入到外部 table 如果它不存在
INSERT to foreign table if it doesnt exist
我们已经将相当大的 table 规范化为分隔商店名称和产品详细信息,例如:
CREATE TABLE store_products
(
id BIGINT DEFAULT PRIMARY KEY NOT NULL,
storeid INTEGER REFERENCES store(id),
productid BIGINT REFERENCES product_details(id)
producturlid BIGINT REFERENCES product_url(id)
);
我们以 JSON 格式获取商店产品的转储,我们遍历每个项目并通过 Delphi 控制台应用程序将其插入 Postgres。它同时执行此操作(因此 4 个线程插入并通过 JSON 产品数组)。
它首先检查 store
table 中是否存在商店名称,如果不存在,则将其插入并缓存返回的 ID,按名称对 product
执行相同操作 product_url
来自 url.
是否有一种 Postgres 方法可以一次性将数据插入此 table(和外部 table),而无需一一进行所有这些检查?我查看了 CTE (WITH),但我不确定这是解决这个问题的方法。
代码的来回性质以及它在事务中变得很重。
有一些 older SO posts that are similar, but the solutions don't seem to be viable. The one I'm looking at seems to be this one 使用 USPERT 和 CTE。
经过一番尝试后,我确定了这个 Whosebug post 的答案。
@Erwin Brandstetter 的 Function with UPSERT in Postgres 9.5
给出了答案,这是一个多么棒的方法!太厉害了
我们已经将相当大的 table 规范化为分隔商店名称和产品详细信息,例如:
CREATE TABLE store_products
(
id BIGINT DEFAULT PRIMARY KEY NOT NULL,
storeid INTEGER REFERENCES store(id),
productid BIGINT REFERENCES product_details(id)
producturlid BIGINT REFERENCES product_url(id)
);
我们以 JSON 格式获取商店产品的转储,我们遍历每个项目并通过 Delphi 控制台应用程序将其插入 Postgres。它同时执行此操作(因此 4 个线程插入并通过 JSON 产品数组)。
它首先检查 store
table 中是否存在商店名称,如果不存在,则将其插入并缓存返回的 ID,按名称对 product
执行相同操作 product_url
来自 url.
是否有一种 Postgres 方法可以一次性将数据插入此 table(和外部 table),而无需一一进行所有这些检查?我查看了 CTE (WITH),但我不确定这是解决这个问题的方法。
代码的来回性质以及它在事务中变得很重。
有一些 older SO posts that are similar, but the solutions don't seem to be viable. The one I'm looking at seems to be this one 使用 USPERT 和 CTE。
经过一番尝试后,我确定了这个 Whosebug post 的答案。
@Erwin Brandstetter 的 Function with UPSERT in Postgres 9.5
给出了答案,这是一个多么棒的方法!太厉害了