我想从两个表中选择所有列,让我们说表A和表B,其中A的列名不等于B的列名。我试图找到一个解决方案,但我找到的是如何获得常见的列。
select A.COLUMN_NAME
from INFORMATION_SCHEMA.COLUMNS A
join INFORMATION_SCHEMA.COLUMNS B
on A.COLUMN_NAME = B.COLUMN_NAME
where A.TABLE_NAME = 'table1'
and B.TABLE_NAME = 'table2'
我不希望所有这些列都出现,其名称很常见,但是希望所有其他列的名称不相同。
答案 0 :(得分:1)
在where子句中使用相关的not exists
来获取Table2中Table2中不存在的列。
select A.COLUMN_NAME
from INFORMATION_SCHEMA.COLUMNS as A
where A.TABLE_NAME = 'Table1' and
not exists (
select *
from INFORMATION_SCHEMA.COLUMNS as B
where A.COLUMN_NAME = B.COLUMN_NAME and
B.TABLE_NAME = 'Table2'
)
要从两个表中获取列,您可以使用上述查询两次,并将结果与union all
合并。
select A.COLUMN_NAME
from INFORMATION_SCHEMA.COLUMNS as A
where A.TABLE_NAME = 'Table1' and
not exists (
select *
from INFORMATION_SCHEMA.COLUMNS as B
where A.COLUMN_NAME = B.COLUMN_NAME and
B.TABLE_NAME = 'Table2'
)
union all
select A.COLUMN_NAME
from INFORMATION_SCHEMA.COLUMNS as A
where A.TABLE_NAME = 'Table2' and
not exists (
select *
from INFORMATION_SCHEMA.COLUMNS as B
where A.COLUMN_NAME = B.COLUMN_NAME and
B.TABLE_NAME = 'Table1'
)
或者您可以将except
与union all
一起使用。
select COLUMN_NAME
from (
select COLUMN_NAME
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME = 'Table1'
except
select COLUMN_NAME
from INFORMATION_SCHEMA.COLUMNS as A
where TABLE_NAME = 'Table2'
) as C
union all
select COLUMN_NAME
from (
select COLUMN_NAME
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME = 'Table2'
except
select COLUMN_NAME
from INFORMATION_SCHEMA.COLUMNS as A
where TABLE_NAME = 'Table1'
) as C
答案 1 :(得分:1)
;WITH A AS(
select COLUMN_NAME
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME = 'table1'
),
B AS(
select COLUMN_NAME
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME = 'table2'
)
SELECT A.COLUMN_NAME FROM A
LEFT OUTER JOIN B
ON A.COLUMN_NAME = B.COLUMN_NAME
WHERE B.COLUMN_NAME IS NULL
UNION ALL
SELECT B.COLUMN_NAME FROM A
RIGHT OUTER JOIN B
ON A.COLUMN_NAME = B.COLUMN_NAME
WHERE A.COLUMN_NAME IS NULL