PostgreSQL视图使用特殊名称作字段时的处理

有PostgreSQL的视图在使用诸如如NAME、COMMENTS等特殊名称但非关键字作为字段名时,本身并不禁止,但在使用时有许多限制。

假设原始表为:

create table t
(
  id int not null primary key, 
  name varchar(20),
  comments varchar(100)
);

如果按如下定义创建视图:

create or replace view v1 as
select 
  t.id id,
  t.name name, 
  t.comments comments
from t
where ...

则会报语法错误,应该是与语法解释器的定义有关。解决方法有三:

  1. 指定字段别名为其它名称,如t.name  name_, t.comments comments_ ...;
  2. 直接使用表字段名而不指定字段别名,如:t.name, t.comments...;
  3. 指定字段别名时使用AS关键字,如t.name  as name, t.comments as comments ...

方法一对使用该视图的程序代码都可能产生影响,一般情况下不建议采用;

方法二有一定局限性,当从两个含有同名的表连接产生新视图时,会产生混乱:

create or replace view v2 as
select 
  t1.id ,
  t1.name , 
  t2.name
from t1, t2
where t1.id = t2.id ...

方法三则不存在前两种方法的缺点,因此适用性最好,推荐采用。

需要说明的是,一旦按方法一创建了视图,再将其字段名称改回来,直接用create or replace是不行的,会报“can't rename column from name_ to name”之类的错误。此时必须明确删掉原视图再重新创建:

create or replace view v3 as
select 
  t.id id,
  t.name name_, 
  t.comments comments_
from t
where ...;

drop view v3; 

create view v3 as
select 
  t.id id,
  t.name as name, 
  t.comments as comments
from t
where ...;

对此,最佳方案还是:最初建表时就避免用NAME, COMMENTS等特殊名称作字段名,可以省却以后的诸多麻烦。

posted @ 2017-10-30 17:59  闻歌感旧  阅读(1228)  评论(0编辑  收藏  举报