我有4个具有相似模式的数据库,我正在尝试创建一个查询,只返回仅存在于数据库1中的表,列对,而不存在于数据库2,3或4中。
目前,我可以通过以下查询返回数据库1和2之间的对称差异...
select table_name, column_name from (
select table_name, column_name from [Database1].information_schema.columns
union all
select table_name, column_name from [Database2].information_schema.columns) as tmp
group by table_name, column_name having count(*) = 1
但是,在尝试仅隔离数据库1中的那些列并在所有4个数据库中执行相同操作时,事情变得越来越复杂。这个查询最干净的解决方案是什么?
答案 0 :(得分:1)
SELECT
D1.table_name,
D1.column_name
FROM
Database1.information_schema.columns D1
LEFT OUTER JOIN Database2.information_schema.columns D2 ON
D2.table_name = D1.table_name AND
D2.column_name = D1.column_name
LEFT OUTER JOIN Database3.information_schema.columns D3 ON
D3.table_name = D1.table_name AND
D3.column_name = D1.column_name
LEFT OUTER JOIN Database4.information_schema.columns D4 ON
D4.table_name = D1.table_name AND
D4.column_name = D1.column_name
WHERE
D2.table_name IS NULL AND
D3.table_name IS NULL AND
D4.table_name IS NULL
答案 1 :(得分:1)
我可以在第一次拍摄时提出这个问题,这可能是一个良好的开端。这还没有经过测试,只是另一种选择:
select table_name, column_name from [Database1].information_schema.columns d1
where table_name || '+' || column_name
not in (select table_name || '+' || column_name from [Database2].information_schema.columns)
and table_name || '+' || column_name
not in (select table_name || '+' || column_name from [Database3].information_schema.columns)
and table_name || '+' || column_name
not in(select table_name || '+' || column_name from [Database4].information_schema.columns)