【问题标题】:snowflake, get a list of mismatching columns between two tables (SQL)雪花,获取两个表之间不匹配列的列表(SQL)
【发布时间】:2017-10-10 09:09:54
【问题描述】:

我一直在做一些研究,但没有找到太多。我需要比较两个表以获取表 1 中的列列表,但表 2 中没有。我使用的是雪花。 现在,我找到了这个答案:postgresql - get a list of columns difference between 2 tables

问题是当我运行代码时出现这个错误:

SQL compilation error: invalid identifier TRANSIENT_STAGE_TABLE

如果我单独运行代码可以正常运行,所以如果我运行:

SELECT column_name
FROM information_schema.columns 
WHERE table_schema = 'your_schema' AND table_name = 'table2'

我实际上得到了一个列名列表,但是当我将它链接到第二个表达式时,会返回上述错误。 关于发生了什么的任何提示? 谢谢

【问题讨论】:

    标签: sql snowflake-cloud-data-platform


    【解决方案1】:

    原始帖子中的查询应该可以工作,也许您在某处缺少单引号?看这个例子

    create or replace table xxx1(i int, j int);
    create or replace table xxx2(i int, k int);
    
    -- Query from the original post
    SELECT column_name
    FROM information_schema.columns 
    WHERE table_name = 'XXX1'
        AND column_name NOT IN
        (
            SELECT column_name
            FROM information_schema.columns 
            WHERE table_name = 'XXX2'
        );
    -------------+
     COLUMN_NAME |
    -------------+
     J           |
    -------------+
    

    您还可以编写一个稍微复杂的查询来查看两个表中所有不匹配的列:

    with 
    s1 as (
      select table_name, column_name 
      from information_schema.columns 
      where table_name = 'XXX1'), 
    s2 as (
      select table_name, column_name 
      from information_schema.columns 
      where table_name = 'XXX2') 
    select * from s1 full outer join s2 on s1.column_name = s2.column_name;
    ------------+-------------+------------+-------------+
     TABLE_NAME | COLUMN_NAME | TABLE_NAME | COLUMN_NAME |
    ------------+-------------+------------+-------------+
     XXX1       | I           | XXX2       | I           |
     XXX1       | J           | [NULL]     | [NULL]      |
     [NULL]     | [NULL]      | XXX2       | K           |
    ------------+-------------+------------+-------------+
    

    当然,您可以添加WHERE s1.column_name IS NULL or s2.column_name IS NULL 以仅查找缺失的列。

    您还可以轻松扩展它以检测列类型差异。

    【讨论】:

      猜你喜欢
      • 2017-12-16
      • 1970-01-01
      • 2021-01-11
      • 2022-07-26
      • 2019-09-22
      • 2012-10-04
      • 1970-01-01
      • 1970-01-01
      • 2015-05-23
      相关资源
      最近更新 更多