【发布时间】:2021-09-24 17:23:09
【问题描述】:
有 2 个表在两个表中都有 10 列,表 2 中存在 2 列但表 1 中不存在。我有一个任务需要获取表 2 中存在但表 1 中不存在的这 2 列. 查询条件为:
- 我们必须使用 information_schema.columns 表。
- 必须在同一张表 information_schema.columns 上使用左连接
【问题讨论】:
有 2 个表在两个表中都有 10 列,表 2 中存在 2 列但表 1 中不存在。我有一个任务需要获取表 2 中存在但表 1 中不存在的这 2 列. 查询条件为:
【问题讨论】:
一种简单的方法是取表 2 中所有不在表 1 中的列。
SELECT c.COLUMN_NAME
FROM information_schema.tables t
join INFORMATION_SCHEMA.COLUMNS c on t.TABLE_NAME = c.TABLE_NAME
WHERE t.TABLE_NAME = 'table2' and c.COLUMN_NAME not in
(
SELECT c.COLUMN_NAME
FROM information_schema.tables t
join INFORMATION_SCHEMA.COLUMNS c on t.TABLE_NAME = c.TABLE_NAME
WHERE t.TABLE_NAME = 'table1'
)
【讨论】:
根据您的要求,此问题有多种解决方案。给个简单的:
在table_name 和column_names 上左连接information_schema.columns 表,然后使用where not exists 从连接结果中过滤掉'table1' 的列。最后对合并的结果应用另一个过滤器,只取 'table2' 中的 column_name:
select isc1.column_name from information_schema.columns isc1
left join information_schema.columns isc2
on isc1.table_name = isc2.table_name and isc1.column_name = isc2.column_name
where not exists (select column_name
from information_schema.columns isc
where isc.table_name = 'table1')
and isc1.table_name = 'table2';
【讨论】:
SELECT *
FROM INFORMATION_SCHEMA.COLUMNS t2
LEFT JOIN INFORMATION_SCHEMA.COLUMNS t1
ON t2.COLUMN_NAME = t1.COLUMN_NAME
AND t1.TABLE_NAME = 'table1'
WHERE t2.TABLE_NAME = 'table2'
AND t1.COLUMN_NAME IS NULL;
【讨论】: