代码之家  ›  专栏  ›  技术社区  ›  Zakhar

带有列引用的歧义

  •  2
  • Zakhar  · 技术社区  · 6 年前

    我尝试运行以下简单代码:

    Create Table weather (
        city        varchar(80),
        temp_lo     int,
        temp_hi     int,
        prcp        real,
        date        date
    );
    Insert Into weather Values ('A', -5, 40, 25, '2018-01-10');
    Insert Into weather Values ('B', 5, 45, 15, '2018-02-10');
    
    Create Table cities (
        city        varchar(80),
        location    point
    );
    Insert Into cities Values ('A', '(12,10)');
    Insert Into cities Values ('B', '(6,4)');
    Insert Into cities Values ('C', '(18,13)');
    
    Select * From cities, weather Where city = 'A'
    

    但我得到的是

    错误:列引用“city”不明确。

    我的代码有什么问题?

    2 回复  |  直到 6 年前
        1
  •  6
  •   Phil    6 年前

    create table cities (
        city_id     integer primary key,
        city_name   varchar(100), 
        location    point
    );
    

    Create Table weather (
        city_id     integer,
        temp_lo     int,
        temp_hi     int,
        prcp        real,
        record_date  date
    );
    

    date SQL reserved words

    Insert Into weather Values (1, -5, 40, 25, '2018-01-10');
    Insert Into weather Values (2, 5, 45, 15, '2018-02-10');
    
    Insert Into cities Values (1,'A', '(12,10)');
    Insert Into cities Values (2,'B', '(6,4)');
    Insert Into cities Values (3,'C', '(18,13)');
    

    Select * From cities, weather Where city = 'A'
    

    city cartesian product

    Select * 
    From cities, weather 
    Where cities.city_id = weather.city_id
    and city_name = 'A';
    

    Select * 
    From cities
    join weather on cities.city_id = weather.city_id
    Where city_name = 'A';
    

    where

        2
  •  5
  •   EzLo tumao kaixin    6 年前

    cities weather city WHERE city = 'A' 是指什么?

    通过在列前面加上表名,可以告诉引擎要筛选哪个列:

    Select * From cities, weather Where cities.city = 'A'
    

    您还可以引用别名为的表:

    Select * 
    From cities AS C, weather AS W 
    Where C.city = 'A'
    

    但最重要的是,确保 将表格连接在一起 ,除非您希望两个表中的所有记录都不使用条件进行匹配(笛卡尔积)。你可以用显式连接它们 INNER JOIN :

    Select 
        * 
    From 
        cities AS C
        INNER JOIN weather AS W ON C.city = W.city
    Where 
        C.city = 'A'
    

    在您提到的示例中,使用此查询:

    SELECT *
    FROM weather, cities
    WHERE city = name;
    

    但在这里, 城市 表有 name 列(而不是 城市 哪个是那个 使用)。所以这个 哪里 子句正在链接 天气 城市 一起吃饭,因为 城市 天气 列和 名称 城市 列和不存在歧义,因为两列的名称不同。