这是你如何做到的。假设...具有空数据的列...您的意思是包含NULL
所有行的值的列。
DELIMITER $$
CREATE PROCEDURE sp_select()
BEGIN
SET @tbl = 'tbl1', @sql = NULL, @cols = NULL;
SELECT
GROUP_CONCAT(
CONCAT(
'SELECT ''',
`column_name`,
''' name, COUNT(',
`column_name`, ') n FROM ',
@tbl
)
SEPARATOR ' UNION ALL ') INTO @sql
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = @tbl;
SET @sql = CONCAT(
'SELECT GROUP_CONCAT(name) INTO @cols FROM (',
@sql,
') q WHERE q.n > 0'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
SET @sql = CONCAT('SELECT ', @cols, ' FROM ', @tbl);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;
然后你调用程序
CALL sp_select();
你会得到
+-----+------+------+
| 姓名 | val1 | val3 |
+-----+------+------+
| 一个 | 1 | 2 |
| 乙 | 4 | 4 |
| c | 5 | 7 |
| 电子| 7 | 6 |
+-----+------+------+
这是SQLFiddle演示。