postgresql - 每个唯一值执行一次函数

标签 postgresql function

我有两个表,其中包含与日常业务相关的数据:

CREATE TABLE main_table (
  main_id serial,
  cola text,
  colb text,
  colc text,
  CONSTRAINT main_table_pkey PRIMARY KEY (main_id)
);

CREATE TABLE second_table (
  second_id serial,
  main_id integer,
  cold text,
  CONSTRAINT second_table_pkey PRIMARY KEY (second_id),
  CONSTRAINT second_table_fkey FOREIGN KEY (main_id)
    REFERENCES main_table (main_id) MATCH SIMPLE
    ON UPDATE NO ACTION ON DELETE NO ACTION
);

我们需要知道这些表中的某些数据何时更新,以便可以生成导出并将其推送给第三方。我创建了第三个表来保存更新信息:

CREATE TYPE field AS ENUM ('cola', 'colb', 'colc', 'cold');
CREATE TABLE table_updates (
  main_id int,
  field field
  updated_on date NOT NULL DEFAULT NOW(),
  CONSTRAINT table_updates_fkey FOREIGN KEY (main_id)
    REFERENCES main_table (main_id) MATCH SIMPLE
    ON UPDATE NO ACTION ON DELETE NO ACTION
);

main_tableUPDATE 查询之前有一个触发器来更新 table_updates,这满足了跟踪四列更新中的三列的需要。

我可以轻松地将相同类型的触发器添加到 second_table,但是由于 main_id 不是唯一的,因此该函数可以针对单个 main_id< 执行多次 值,这是不可取的。

如何创建一个函数,在更新 second_table 中的多行时,每个 main_id 仅执行一次?

最佳答案

How can I create a function that, when updating several rows in second_table, executes only once per main_id?

如果您的插入是按 main_id 批量插入的,即 INSERT INTO tbl (main_id...) VALUES (main_id ...),(main_id ...),(main_id ...)您可以使用 rule systemINSERTUPDATE

触发一次

For the things that can be implemented by both, which is best depends on the usage of the database. A trigger is fired once for each affected row. A rule modifies the query or generates an additional query. So if many rows are affected in one statement, a rule issuing one extra command is likely to be faster than a trigger that is called for every single row and must re-determine what to do many times. However, the trigger approach is conceptually far simpler than the rule approach, and is easier for novices to get right.

害羞的是,您可能还想查看正常的 LISTEN ,和NOTIFY 。这使您能够使用异步操作。如果这是您的事情,并且您决定保留触发方法,请考虑触发更改通知模块,通过 tcn .

如果可能的话,我的建议是在应用程序中(在数据库之外)执行此操作。请记住,在 PostgreSQL 中,temp 表是 session 本地的。所以你可以让每个加载器 session 做这样的事情,

BEGIN
  CREATE TEMP TABLE UNLOGGED etl_inventory;
  COPY foo FROM stdin;
  -- Are they different, if so `NOTIFY`
  -- UPSERT
COMMIT;

然后,有一个守护进程在收到 NOTIFY 事件时将导出添加到导出队列。

关于postgresql - 每个唯一值执行一次函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43375106/

相关文章:

postgresql - WSOD 即将打开 drupal 7 项目的第一页

postgresql - 如何将 postgres 数据库转换为 sqlite

function - Scala Map,元组和函数参数列表之间的歧义

python - tkinter网格行没有出现并且没有传递到正确的功能

sql - PostgreSQL 和队列命令

database - Postgres 驱动程序在 go 中找不到表

r - 如何为数据整理编写有效的包装器,允许在调用包装器时关闭任何包装的部分

c++数组传递困境

JavaScript 函数参数

java - 为什么@NaturalId 不在数据库中创建唯一约束?