伪:
select * from foo where [every column is not null]
有没有办法在不指定实际列名的情况下做到这一点?
我能想到的一个可能的解决方案是使用动态 SQL
SELECT GROUP_CONCAT(column_name SEPARATOR ' IS NOT NULL AND ')
INTO @sql
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_schema = SCHEMA()
AND table_name = 'foo'
GROUP BY table_name;
SET @sql = CONCAT('SELECT * FROM foo WHERE ', @sql, ' IS NOT NULL');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
这是SQLFiddle演示
显然它可以包装到一个带有表名参数的存储过程中
DELIMITER $$
CREATE PROCEDURE sp_select_all_not_null(IN tbl_name VARCHAR(64))
BEGIN
SELECT GROUP_CONCAT(column_name SEPARATOR ' IS NOT NULL AND ')
INTO @sql
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_schema = SCHEMA()
AND table_name = tbl_name
GROUP BY table_name;
SET @sql = CONCAT('SELECT * FROM ', tbl_name, ' WHERE ', @sql, ' IS NOT NULL');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END
DELIMITER ;
然后使用它
CALL sp_select_all_not_null('foo');
这是SQLFiddle演示