如何查找表中哪些记录填充了大多数字段?

时间:2012-09-11 10:12:10

标签: mysql

或者换句话说:如何找到表中哪条记录的空白或空白字段最少?

无需单独计算每个单独的字段 - 表格有161个字段。

2 个答案:

答案 0 :(得分:2)

这可以通过构建动态查询来完成,如:

SELECT id,
       (IF(col1 = NULL OR col1 = "", 1, 0) +
        IF(col2 = NULL OR col3 = "", 1, 0) +
        ...
        IF(coln = NULL OR coln = "", 1, 0)
       ) AS null_count
FROM table_name
ORDER BY null_count DESC
LIMIT 1;

通过使用INFORMATION_SCHEMA.COLUMNS形成新的动态查询,然后执行dynamic sql query,可以轻松完成此操作。此外,您可能需要通过将会话级变量GROUP_CONCAT设置为更高的值来增加group_concat_max_len函数的最大输出长度。

SET GLOBAL group_concat_max_len = 4294967295;

SELECT @query1 := CONCAT('SELECT id,
                                 (',
                         GROUP_CONCAT(CONCAT('IF(',COLUMN_NAME,' IS NULL OR ',
                                                   COLUMN_NAME,' = "", 1, 0
                                                ) 
                                           ') 
                                      SEPARATOR ' + '),
                                ') AS null_count
                         FROM table_name
                         ORDER BY null_count DESC
                         LIMIT 1')
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = SCHEMA()
      AND TABLE_NAME = 'table_name';

PREPARE stmt FROM @query1; EXECUTE stmt; DEALLOCATE PREPARE stmt;

示例:SQLFiddle

答案 1 :(得分:1)

免责声明:我提出错误的问题,认为OP正在寻找具有最多NULL的表的列。尽管如此,它可能对任何人都有用。

创建一个这样的程序:

drop procedure if exists test_most_pop_field;
DELIMITER $$
CREATE PROCEDURE test_most_pop_field(IN tableName varchar(100))
BEGIN

DECLARE done INT DEFAULT 0;
DECLARE sql_query VARCHAR(255);

DECLARE cur CURSOR FOR 
SELECT CONCAT('INSERT INTO tmp_result(columnName, numberOfEmptyRows) SELECT "', COLUMN_NAME, '" AS columnName, SUM(IF(',COLUMN_NAME,' IS NULL OR ', COLUMN_NAME,' = "", 1, 0)) AS numberEmptyRows FROM ', TABLE_NAME)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = SCHEMA()
AND TABLE_NAME = tableName;

DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done = 1;

DROP TABLE IF EXISTS tmp_result;
CREATE TEMPORARY TABLE tmp_result(columnName varchar(100), numberOfEmptyRows int);

OPEN cur;

REPEAT
  FETCH cur INTO sql_query;
  IF NOT done THEN
    BEGIN
      SET @sql = sql_query; /*this extra step is necessary, cause otherwise it's a syntax error, don't ask me why*/
      PREPARE stmt FROM @sql; 
      EXECUTE stmt; 
      DEALLOCATE PREPARE stmt;
    END;
  END IF;
UNTIL done END REPEAT;

CLOSE cur;

SELECT * FROM tmp_result ORDER BY numberOfEmptyRows DESC /*optionally LIMIT 1*/;

END $$
DELIMITER ;

然后使用您要检查的表名称调用它:

CALL test_most_pop_field('yourTableName');