0

我有一个名为 device_statistics 的表,它存储一个应用程序的设备信息,表创建脚本是:

CREATE TABLE public.device_statistics
(
    id character varying(255) COLLATE pg_catalog."default" NOT NULL,
    abnormalcount integer,
    appid character varying(32) COLLATE pg_catalog."default" NOT NULL,
    inactivecount integer,
    offlinecount integer,
    onlinecount integer,
    statisticstime date,
    totalcount integer,
    CONSTRAINT ods_device_statistics_pkey PRIMARY KEY (id)
)

当设备离线时,我必须更新离线计数值,因为totalcount=abnormalcount + inactivecount + offlinecount + onlinecount这样我可以在异常计数、非活动计数、离线计数或在线计数更新时自动更新总计数值。

例如:

在设备离线之前,行如下(仅显示我们需要):

appid  offlinecount totalcount

test        10            32

当设备离线并且我更新离线计数值时,我想要如下行:

appid  offlinecount totalcount
test       9           31

totalcout 的值是自动更新的,怎么办?

4

1 回答 1

0

在 PostgreSQL 12 之前,您可以改为创建视图:

CREATE TABLE public.device_statistics
(
    id character varying(255) COLLATE pg_catalog."default" NOT NULL,
    abnormalcount integer,
    appid character varying(32) COLLATE pg_catalog."default" NOT NULL,
    inactivecount integer,
    offlinecount integer,
    onlinecount integer,
    statisticstime date,
    CONSTRAINT ods_device_statistics_pkey PRIMARY KEY (id)
)

CREATE OR REPLACE VIEW public.device_statistics_with_total AS
SELECT id,
       abnormalcount,
       appid,
       inactivecount,
       offlinecount,
       onlinecount,
       statisticstime,
       abnormalcount + inactivecount + offlinecount + onlinecount AS totalcount
FROM device_statistics;

如果您有能力升级到 PostgreSQL v. 12,您可以使用新的生成列功能

CREATE TABLE public.device_statistics
(
    id character varying(255) COLLATE pg_catalog."default" NOT NULL,
    abnormalcount integer,
    appid character varying(32) COLLATE pg_catalog."default" NOT NULL,
    inactivecount integer,
    offlinecount integer,
    onlinecount integer,
    statisticstime date,
    totalcount integer GENERATED ALWAYS AS (abnormalcount + inactivecount + offlinecount + onlinecount) STORED,
    CONSTRAINT ods_device_statistics_pkey PRIMARY KEY (id)
)

披露:我为EnterpriseDB (EDB)工作

于 2019-10-28T07:20:17.860 回答