2014-10-31 40 views
0

如果該字段在源表中不存在,是否可以將SERIAL列添加到現有視圖?我想獲得一個名爲OID的autoincremental ID字段,它不能爲NULL。添加不存在的列以查看

CREATE OR REPLACE VIEW public.osm_polygon AS 

SELECT planet_osm_polygon.osm_id::text AS osm_id, 
    planet_osm_polygon.tags -> 'osm_timestamp'::text AS osm_timestamp, 
    planet_osm_polygon.tags -> 'name:en'::text AS name_en, 
    planet_osm_polygon.access, planet_osm_polygon.admin_level, 
    planet_osm_polygon.aerialway, planet_osm_polygon.aeroway, 
    planet_osm_polygon.amenity, planet_osm_polygon.area, 
    planet_osm_polygon.barrier, planet_osm_polygon.bicycle, 
    planet_osm_polygon.brand, planet_osm_polygon.bridge, way 
    planet_osm_polygon.boundary, planet_osm_polygon.building FROM planet_osm_polygon 
WHERE st_isvalid(planet_osm_polygon.way) AND planet_osm_polygon.way && st_makeenvelope((-17.5)::double precision, 3.0::double precision, 8.7::double precision, 26.9::double precision, 4326); 

這就是我的看法。

我需要添加一個包含自動增量字段作爲長整數或串不能爲NULL的列。有什麼建議麼?

+0

如何使用'row_number()'? http://www.postgresql.org/docs/current/static/tutorial-window.html – 2014-10-31 13:38:05

+0

在底層表中添加列,然後將其包含在「VIEW」定義中。 – 2014-10-31 13:39:28

+0

儘管如此,不要將它稱爲「OID」列。這通常用作內部的「對象標識符」,並被專門處理。不要混淆事物。 – 2014-10-31 18:46:50

回答

1

使用row_number

CREATE OR REPLACE VIEW public.osm_polygon AS 

SELECT planet_osm_polygon.osm_id::text AS osm_id, 
planet_osm_polygon.tags -> 'osm_timestamp'::text AS osm_timestamp, 
planet_osm_polygon.tags -> 'name:en'::text AS name_en, 
planet_osm_polygon.access, planet_osm_polygon.admin_level, 
planet_osm_polygon.aerialway, planet_osm_polygon.aeroway, 
planet_osm_polygon.amenity, planet_osm_polygon.area, 
planet_osm_polygon.barrier, planet_osm_polygon.bicycle, 
planet_osm_polygon.brand, planet_osm_polygon.bridge, way, 
planet_osm_polygon.boundary, planet_osm_polygon.building, 
row_number() over() as row_num 
FROM planet_osm_polygon 
WHERE st_isvalid(planet_osm_polygon.way) AND planet_osm_polygon.way && st_makeenvelope((-17.5)::double precision, 3.0::double precision, 8.7::double precision, 26.9::double precision, 4326); 
+1

您應該爲'row_number()'添加某種排序。也許'order by planet_osm_polygon.osm_id'?否則,它可以爲不同的執行返回不同的結果。 – 2014-10-31 14:36:12

+1

@IgorRomanchenko:一般來說,我同意你'row_number()'只有'order by'纔有意義。但是,視圖中生成的數字無論如何都不會穩定。想想行被刪除或插入到底層表中(真正的問題是:row_number()是否足夠用於josh?) – 2014-10-31 14:58:40