表2中有两个表共有10列,表2中有2列,但表1中没有。我有一项任务,需要在表2中得到这2列,而不是在表1中。查询的条件是:
我们必须使用information_schema.columns表。必须在同一个表中使用
发布于 2021-07-15 19:59:54
一种简单的方法是获取表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'
)发布于 2021-07-15 20:10:57
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;发布于 2021-07-15 20:42:31
根据您的要求,需要对此问题提供多个解决方案。只是简单地说一句:
左加入information_schema.columns表,并在table_name和column_names上使用它自己,然后从联合结果中使用where not exists过滤出'table1'的列。最后,在已连接的结果上应用另一个筛选器,使其只接受位于column_name中的'table2'
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';https://stackoverflow.com/questions/68399957
复制相似问题