QGIS加载与编辑视图图层

1、数据准备

在PostGIS中导入点层数据valve,valve表中拥有字段(gid,oldno1,subtype,diameter,addr,geom),并建立valve的属性扩展表valve_ext

创建扩展表

--DROP SEQUENCE waterdataset.valve_ext_seq;
CREATE SEQUENCE waterdataset.valve_ext_seq
    INCREMENT 1
    START 1
    MINVALUE 1
    MAXVALUE 2147483647
    CACHE 1;
 
ALTER SEQUENCE waterdataset.valve_ext_seq
    OWNER TO postgres;

-- Table: waterdataset.valve_ext
--DROP TABLE waterdataset.valve_ext;
CREATE TABLE waterdataset.valve_ext
(
    id integer NOT NULL DEFAULT nextval('waterdataset.valve_ext_seq'::regclass),
    gid integer NOT NULL,
    extname character(50) COLLATE pg_catalog."default",
    CONSTRAINT valve_ext_pkey PRIMARY KEY (id)
        USING INDEX TABLESPACE sy_water,
    CONSTRAINT gid_unique UNIQUE (gid)
        USING INDEX TABLESPACE sy_water
)
WITH (
    OIDS = FALSE
)

TABLESPACE sy_water;
ALTER TABLE waterdataset.valve_ext
    OWNER to postgres;

 2、创建视图

基于点表valve和属性扩展表valve_ext建立视图valveview

--创建视图
CREATE OR REPLACE VIEW waterdataset.valveview AS
 SELECT t1.gid,
    t1.oldno1,
    t1.subtype,
    t1.diameter,
    t1.addr,
    t1.geom,
    t2.extname
   FROM waterdataset.valve t1
     LEFT JOIN waterdataset.valve_ext t2 ON t1.gid = t2.gid;

ALTER TABLE waterdataset.valveview
    OWNER TO postgres;

3、在QGIS中加载视图图层

在qgis中加载视图图层,启动图层编辑,编辑属性后提示不是简单视图,需要通过规则或触发器来制定更新、插入、删除命令。

 

 

 

4、建立视图的编辑规则

PostgreSQL规则语法

CREATE [ OR REPLACE ] RULE name AS ON event
    TO table [ WHERE condition ]
DO [ ALSO | INSTEAD ] { NOTHING | command | ( command ; command ... ) }

基于以上语法我们创建视图的编辑规则,以update命令为例

因为我们的视图需要更新两个表,主表valve与扩展属性表valve_ext,所以在DO INSTAEAD后我们需要执行多条命令,按照语法在()中以分号分隔多条命令。

更新实现逻辑更新属性后先更新主表valve属性,然后更新valve_ext属性(如果不存在则插入,这里用到了PostgreSQL的upsert特性)

CREATE OR REPLACE RULE valveview_upd AS
    ON UPDATE TO waterdataset.valveview
    DO INSTEAD
( UPDATE waterdataset.valve 
  SET gid = new.gid, oldno1 = new.oldno1, subtype = new.subtype, diameter = 
  new.diameter, addr = new.addr, geom = new.geom
  WHERE valve.gid = old.gid;
  INSERT INTO waterdataset.valve_ext (gid, extname)
  VALUES (new.gid, new.extname) ON CONFLICT(gid) DO UPDATE SET gid = excluded.gid, extname = excluded.extname;
);
--EXCLUDED upsert语法中待插入的数据对象关键字

PostgreSQL的upsert语法

INSERT INTO table VALUES(…) ON CONFLICT(唯一字段)DO UPDATE SET

建立好规则后更新视图成功

UPDATE waterdataset.valveview SET gid=517,oldno1 = '1005',extname='扩展属性'
WHERE gid = 517;

UPDATE 1 耗时54 msec 成功返回查询

 

posted @ 2019-10-10 09:07  GoodGF  阅读(2240)  评论(0编辑  收藏  举报