如果MySQL查询的所有字段均为Null(或零),是否有任何方法不获取列?或以任何方式从查询结果中删除此类列?
例如我有不同的表,一个可能看起来像这样:
____________________________________________
| id | value1 | value2 | value3 | value4 |
--------------------------------------------
| 1 | 3 | 0 | A | Null |
| 2 | 5 | 0 | B | Null |
| 3 | 0 | 0 | C | Null |
| 4 | 9 | 0 | D | Null |
| 5 | 7 | 0 | Null | Null |
| 6 | 9 | 0 | E | Null |
--------------------------------------------
我最后需要这样的东西:
__________________________
| id | value1 | value3 |
--------------------------
| 1 | 3 | A |
| 2 | 5 | B |
| 3 | 0 | C |
| 4 | 9 | D |
| 5 | 7 | Null |
| 6 | 9 | E |
--------------------------
谢谢。
最佳答案
从技术上讲,您可以使用动态SQL来做到这一点,但是是否必须继续使用这种方法却值得怀疑。
DELIMITER $$
CREATE PROCEDURE sp_select_not_empty(IN tbl_name VARCHAR(64))
BEGIN
SET @sql = NULL, @cols = NULL;
SELECT
GROUP_CONCAT(
CONCAT(
'SELECT ''',
column_name,
''' name, COUNT(NULLIF(',
column_name, ', ',
CASE WHEN data_type IN('int', 'decimal') THEN 0 WHEN data_type IN('varchar', 'char') THEN '''''' END,
')) n FROM ',
tbl_name
)
SEPARATOR ' UNION ALL ') INTO @sql
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = tbl_name;
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_not_empty('Table1');
然后我们得到
+ ------ + -------- + -------- +
| id | value1 | value3 |
+ ------ + -------- + -------- +
| 1 | 3 | A |
| 2 | 5 | B |
| 3 | 0 | C |
| 4 | 9 | D |
| 5 | 7 | NULL |
| 6 | 9 | E |
+ ------ + -------- + -------- +