PostgreSQL 仅当新值与旧值不同时才插入

问题描述 投票:0回答:1

在 Postgres 中,我有一个像这样的遥测表:

        time         |     name     | slave_id |       type       | fCounter
---------------------+--------------+----------+------------------+----------
 2024-05-14 11:20:30| FoobarCounter | 1        | holding_register |      101
 2024-05-14 11:20:20| FoobarCounter | 1        | holding_register |      101   <<--
 2024-05-14 11:20:10| FoobarCounter | 1        | holding_register |      100
 2024-05-14 11:20:00| FoobarCounter | 1        | holding_register |      100

Telegraf 默认情况下每 10 秒插入一个新行,但实际测量值(存储在

fCounter
中)每隔几个小时更新一次。所以我想限制对数据库的插入,只存储新的(更新的)值和时间,当它发生时:

首先,我创建新表:

CREATE TABLE foobar_counter (
    time timestamp without time zone,
    value bigint NOT NULL
);

然后我创建一个函数:

CREATE OR REPLACE FUNCTION insert_function(timestamp without time zone, text, text, text, bigint)
    RETURNS VOID
    AS $$ INSERT INTO foobar_counter VALUES  ($1, $5) $$
    LANGUAGE SQL;

和触发器:

CREATE OR REPLACE TRIGGER insert_trigger
    BEFORE INSERT ON modbus
    FOR EACH ROW
    WHEN (foobar_counter.value IS DISTINCT FROM NEW."fCounter")
    EXECUTE FUNCTION insert_function();

但是失败并出现错误:

ERROR:  invalid reference to FROM-clause entry for table "foobar_counter"
LINE 4:     WHEN (foobar_counter.value IS DISTINCT FROM NEW."nCounter...

实际上我不确定这是否是最简单/合适的方法

sql postgresql
1个回答
0
投票

unique
 上创建一个 
(name, slave_id , type, fCounte)

索引

并使用

insert into telemetry (name, slave_id, type, fCounte) 
VALUEs ( 'FoobarCounter' . 1 , 'holding_register' , 101)
on conflict do nothing;

要插入新数据,这可以防止您在这四列上插入重复数据。

你也可以考虑标准化你的结构

© www.soinside.com 2019 - 2024. All rights reserved.