如何获取 MySQL 服务器上每个数据库的空值计数?

How can I get count of nulls per database on a MySQL server?

我想获得 MySQL 服务器上每个数据库的所有列和 table 的空值计数。结果 table 应如下所示:

+---------------+------------+
| database_name | null_count |
+---------------+------------+
| database1     |          0 |
| database2     |       5643 |
| database3     |         72 |
+---------------+------------+

但是,我无法为单个 table:

获取超出空值的计数
SELECT concat('select', group_concat(' count(*) - count(', column_name, ') '  SEPARATOR ' + '), 'from ', MAX(table_schema), '.', MAX(TABLE_NAME))
INTO @SQL
FROM information_schema.columns
WHERE TABLE_SCHEMA = 'Accidents'
AND TABLE_NAME = 'nesreca';

PREPARE stmt FROM @SQL;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

你有什么想法吗?

PS:我能够用 MATLAB 代码得到结果。但是,MySQL 内的解决方案将是更可取的。

我认为您在动态 SQL 方面走在正确的轨道上。因为您想要整个数据库而不是单个 table,所以查询的结构类似于:

select table_schema, sum(cnt)
from (select "table_schema", count(*) as cnt from "table_name" where "column_name" is null union all
      . . .
     ) t
group by table_schema;

您可以将其构建为:

set group_concat_max_len=1500000;
set @subSQL = '(select "@table_schema" as table_schema, count(*) as cnt from `@table_schema`.`@table_name` where `@column_name` is null)';

select @subSQL := group_concat(replace(replace(replace(@subSQL, '@table_schema', table_schema
                                                      ), '@table_name', table_name
                                              ), '@column_name', column_name
                                      ) separator ' union all '
                              )
from information_schema.columns;

set @SQL = concat('select table_schema, sum(cnt) as NumNulls from (',
                  @subSQL,
                  ') t group by table_schema');

PREPARE stmt FROM @SQL;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

我应该注意到 group_concat() 的中间值的默认长度对于此查询可能太小了。你将不得不调整它。系统变量是group_concat_max_len(参见here)。