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

后端 未结 6 1417
太阳男子
太阳男子 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:33

    I am not an expert in SQL procedures, hence giving general idea using SQL queries and a PHP/python script.

    • use SHOW TABLES or some other query on INFORMATION_SCHEMA database to get all tables in your database MY_DATABASE

    • do a query to generate a statement to get all column names in a particular table, this will be used in next query.

     SELECT Group_concat(Concat( "MAX(", column_name, ")" ))
             FROM   information_schema.columns
             WHERE  table_schema = 'MY_DATABSE'
                    AND table_name = 'MY_TABLE'
             ORDER  BY table_name,ordinal_position
    
    • You will get an output like MAX(column_a),MAX(column_b),MAX(column_c),MAX(column_d)

    • Use this output to generate final query :

    SELECT Max(column_a), Max(column_b), Max(column_c), Max(column_d) FROM MY_DATABASE.MY_TABLE

    The output would be :

       MAX(column_a)    MAX(column_b)   MAX(column_c)   MAX(column_d)
         NULL            1           NULL                1
    
    • All the columns with Max value as NULL are the ones which have all values NULL

提交回复
热议问题