【问题标题】:How to get uncommon columns in 2 tables using left joins and information_schema.columns?如何使用左连接和 information_schema.columns 获取 2 个表中的不常见列?
【发布时间】:2021-09-24 17:23:09
【问题描述】:

有 2 个表在两个表中都有 10 列,表 2 中存在 2 列但表 1 中不存在。我有一个任务需要获取表 2 中存在但表 1 中不存在的这 2 列. 查询条件为:

  1. 我们必须使用 information_schema.columns 表。
  2. 必须在同一张表 information_schema.columns 上使用左连接

【问题讨论】:

    标签: sql join left-join


    【解决方案1】:

    一种简单的方法是取表 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'
    )
    

    【讨论】:

    • 哇!发现。谢谢你。你救了我在工作中的巨大挣扎。再次感谢。
    • 您没有在查询中使用,您可以重新检查并修改您的答案
    【解决方案2】:

    根据您的要求,此问题有多种解决方案。给个简单的:

    table_namecolumn_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';
    

    【讨论】:

      【解决方案3】:
      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;
      

      【讨论】:

        猜你喜欢
        • 2020-08-23
        • 2017-10-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-30
        • 1970-01-01
        • 2015-12-03
        • 1970-01-01
        相关资源
        最近更新 更多