如何在视图中添加ROW_NUMBER()?

时间:2013-01-18 07:06:29

标签: sql postgresql sql-view row-number

在PostgreSQL 8.4中我想从3个带id的表创建一个视图。所以我想在我看来有这个结构:

num serial,
name_dispatcher character varying(250)
the_geom geometry

我可以从表中选择name_dispatcherthe_geom

 CREATE VIEW lineView
      AS SELECT 'name' AS name_dispatcher, the_geom
      FROM line1
      UNION
      SELECT 'name' AS name_dispatcher, the_geom
      FROM line2
      UNION
      SELECT 'name' AS name_dispatcher, the_geom
      FROM line3

如何在视图中创建num列?

更新

我找到了解决方案:

ROW_NUMBER() OVER(ORDER BY lineView.voltage)

但我不知道如何在ALTER VIEW中使用它。我怎么把它放在那里?

1 个答案:

答案 0 :(得分:9)

您无法使用ALTER VIEW删除或添加列。我引用the manual on ALTER VIEW

  

ALTER VIEW更改视图的各种辅助属性。 (如果你   想要修改视图的定义查询,请使用CREATE OR REPLACE VIEW。)

但简单的CREATE OR REPLACE VIEW不会削减它。 Another quote from the manual

  

新查询必须生成由其生成的相同列   现有的查看视图

DROPCREATE视图:

DROP VIEW lineview;

CREATE VIEW lineview AS
SELECT *, row_number() OVER(ORDER BY ???) AS num
FROM (
   SELECT 'name' AS name_dispatcher, the_geom
   FROM line1

   UNION
   SELECT 'name' AS name_dispatcher, the_geom
   FROM line2

   UNION
   SELECT 'name' AS name_dispatcher, the_geom
   FROM line3
   ) x

我使用子查询,因为我假设您要将row_number()添加到所有行。在这方面你的问题含糊不清 如果您只想要一个没有特定顺序的唯一ID,请使用row_number() OVER()