我一直在做一些研究,但没有发现太多。我需要比较两个表,得到表1中有哪些列,但表2中没有。我正在使用Snowflake。现在,我找到了这个答案:postgresql-获取两个表之间的列差异列表
问题是,当我运行代码时,我会得到这个错误:
SQL compilation error: invalid identifier TRANSIENT_STAGE_TABLE
如果我单独运行,代码运行良好,所以如果我运行:
SELECT column_name
FROM information_schema.columns
WHERE table_schema = 'your_schema' AND table_name = 'table2'
实际上,我得到了一个列名列表,但当我将其链接到第二个表达式时,会返回上面的错误。有什么线索吗?谢谢
来自原始帖子的查询应该可以工作,也许您在某个地方缺少了单引号?参见此示例
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
来只查找缺少的列。
您还可以轻松地扩展它以检测列类型差异。