Find all those columns which have only null values, in a MySQL table

后端 未结 6 1407
太阳男子
太阳男子 2020-12-08 07:43

The situation is as follows:

I have a substantial number of tables, with each a substantial number of columns. I need to deal with this old and to-be-deprecated data

6条回答
  •  有刺的猬
    2020-12-08 08:42

    You can avoid using a procedure by dynamically creating (from the INFORMATION_SCHEMA.COLUMNS table) a string that contains the SQL you wish to execute, then preparing a statement from that string and executing it.

    The SQL we wish to build will look like:

    SELECT * FROM (
      SELECT 'tableA' AS `table`,
             IF(COUNT(`column_a`), NULL, 'column_a') AS `column`
      FROM   tableA
    UNION ALL
      SELECT 'tableB' AS `table`,
             IF(COUNT(`column_b`), NULL, 'column_b') AS `column`
      FROM   tableB
    UNION ALL
      -- etc.
    ) t WHERE `column` IS NOT NULL
    

    This can be done using the following:

    SET group_concat_max_len = 4294967295; -- to overcome default 1KB limitation
    
    SELECT CONCAT(
             'SELECT * FROM ('
           ,  GROUP_CONCAT(
                'SELECT ', QUOTE(TABLE_NAME), ' AS `table`,'
              , 'IF('
              ,   'COUNT(`', REPLACE(COLUMN_NAME, '`', '``'), '`),'
              ,   'NULL,'
              ,    QUOTE(COLUMN_NAME)
              , ') AS `column` '
              , 'FROM `', REPLACE(TABLE_NAME, '`', '``'), '`'
              SEPARATOR ' UNION ALL '
             )
           , ') t WHERE `column` IS NOT NULL'
           )
    INTO   @sql
    FROM   INFORMATION_SCHEMA.COLUMNS
    WHERE  TABLE_SCHEMA = DATABASE();
    
    PREPARE stmt FROM @sql;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
    

    See it on sqlfiddle.

提交回复
热议问题