由于"重复列" PostgreSql无法创建视图

时间:2014-11-10 00:01:21

标签: postgresql

我正在尝试在每个邻居国家/地区之间创建country_name和country cid对:

这是架构:

CREATE TABLE country (
    cid         INTEGER     PRIMARY KEY,
    cname       VARCHAR(20) NOT NULL,
    height      INTEGER     NOT NULL,
    population  INTEGER     NOT NULL);

CREATE TABLE neighbour (
    country     INTEGER     REFERENCES country(cid) ON DELETE RESTRICT,
    neighbor    INTEGER     REFERENCES country(cid) ON DELETE RESTRICT, 
    length      INTEGER     NOT NULL,
    PRIMARY KEY(country, neighbor));

我的查询:

create view neighbour_pair as (
select c1.cid, c1.cname, c2.cid, c2.cname
from neighbour n join country c1 on c1.cid = n.country
join country c2 on n.neighbor = c2.cid);

我收到错误代码42701,这意味着有一个重复的列。

我得到的实际错误消息是:

ERROR:  column "cid" specified more than once

********** Error **********

ERROR: column "cid" specified more than once
SQL state: 42701

我不确定如何解决错误问题,因为我希望这对邻国拥有国家名称及其cid。

3 个答案:

答案 0 :(得分:1)

没关系。我编辑了查询的第一行并更改了列名

create view neighbour_pair as 

select c1.cid as c1cid, c1.cname as c1name, c2.cid as c2cid, c2.cname as c2name
from neighbour n join country c1 on c1.cid = n.country
join country c2 on n.neighbor = c2.cid;

答案 1 :(得分:1)

我最近遇到了类似的问题。我有一个查询:

CREATE VIEW pairs AS

SELECT p.id, p.name, 
    (SELECT count(id) from results
            where winner = p.id),
    (SELECT count(id) from results
            where winner = p.id OR loser = p.id) 
FROM players p LEFT JOIN matches m ON p.id = m.id
GROUP BY 1,2;

错误告诉我:错误:列“count”指定了多次。查询WAS通过psycopg2工作,但是当我将它带入.sql文件以测试错误时出现。

我意识到我只需要对2个计数子查询进行别名:

CREATE VIEW pairs AS
    SELECT p.id, p.name, 
        (SELECT count(id) from results
                where winner = p.id) as wins,
        (SELECT count(id) from results
                where winner = p.id OR loser = p.id) as matches 
    FROM players p LEFT JOIN matches m ON p.id = m.id
    GROUP BY 1,2;

答案 2 :(得分:0)

您可以在AS使用别名:

例如,您的观点可能如下:

create view neighbour_pair as 
(
select c1.**cid**
     , c1.cname
     , c2.**cid AS cid_c2**
     , c2.cname
from neighbour n 
join country c1 on c1.cid = n.country
join country c2 on n.neighbor = c2.cid
);