【问题标题】:Join 2 tables with several repeated column names- Bigquery (Error: Duplicate column names in the result are not supported)使用多个重复的列名连接 2 个表 - Bigquery(错误:不支持结果中的重复列名)
【发布时间】:2020-05-06 00:50:14
【问题描述】:

我正在使用大查询,需要连接 2 个表,table1 有 14 列,table2 有 16 列。我需要根据 table1.FIPS 和 table2.fip_code 从表 2 中检索值。 2 列的名称相同(列县和列状态,表 1 的值比表 2 多)。 我正在尝试进行外部联接,但由于列名而失败:

*选择 * FROM table1 完全外连接table2 在 table1.FIPS=table2.fip_code 错误为:“不支持结果中的重复列名。发现重复项:县、州”*

我尝试使用别名如下:

*选择 * 除了(县,州), 县 AS 县_一,州 AS 县_二 来自table1 完全外连接table2 在 table1.FIPS=table2.fip_code* 错误是:列名县不明确

有什么建议吗?我不能排除县和州字段,因为我的代码需要它们。

谢谢!

【问题讨论】:

    标签: sql google-bigquery outer-join columnname


    【解决方案1】:

    您可以创建表别名,然后在列名之前使用它来标识您从哪个表中获取列。

    SELECT * EXCEPT(county,state), 
      t1.county AS county_one, 
      t1.state AS county_two,
      t2.* 
    FROM table1 t1
    join table2 t2
    on t1.FIPS = t2.fip_code
    

    【讨论】:

      【解决方案2】:

      如果这些是重复的,您只需将它们从一个表中删除:

      SELECT table1.* EXCEPT (county, state),
             table1.county as county_1, table1.state as state_1
             table2.*
      FROM table1 FULL JOIN
           table2 
           ON table1.FIPS = table2.fip_code;
      

      或者使用REPLACE:

      SELECT table1.* REPLACE (county as count_1, state as state_1),
             table2.*
      FROM table1 FULL JOIN
           table2 
           ON table1.FIPS = table2.fip_code;
      

      或者选择值作为记录:

      SELECT table1, table2
      FROM table1 FULL JOIN
           table2 
           ON table1.FIPS = table2.fip_code;
      

      【讨论】:

      • 谢谢!使用您的语法的选项一有效(不确定它与我使用的 except 语法有什么不同,但这个有效)
      • @Montvidean 。 . .你的有SELECT *,没有指定表名。
      【解决方案3】:

      您的查询:

      SELECT * FROM table1 FULL external join table2 on table1.FIPS= table2.fip_code

      你的目标:

      “我需要根据 table1.FIPS 和 table2.fip_code 从表 2 中检索值”

      一个简单的方法是给你的表名起别名:

      Select 
          t2.*
      --, t1.*  -- you said you only need columns from t2, so I commented this out.     
      From 
          table1 as t1               -- depending on the sql flavor, you may have 
          outer join table2 as t2    -- to omit the 'as' on these lines
          on t1.FIPS = t2.fip_code
      Where
          [add some where stuff here if needed]
      

      【讨论】:

      • 同样的错误“不支持结果中的重复列名。发现重复:县、州”。我的列没有前缀,因此更改表名不会影响列名。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-23
      • 1970-01-01
      • 2020-01-20
      • 1970-01-01
      • 1970-01-01
      • 2016-08-21
      相关资源
      最近更新 更多