我想从我的数据库表中找到具有空列的行。
假设我的表有 10 列和 100 行,这 10 列中的任何一列都可以是 NULL/EMPTY。
所以我不能使用WHERE命令
例如:
SELECT * FROM CUSTOMER WHERE REVENUE IS NULL OR ID IS NULL OR INCOME IS NULL ....(this goes on till 10 columns)
我如何编写此查询来选择具有空值/空值(在任何列中)的行。
最佳答案
表 information_schema.columns
包含系统中每个数据库中每个表的列信息。我们可以从中提取您的表的列名,并使用它来构建准备好的语句,我们可以执行该语句来查找您的值。
假设您的数据库名为foo
,您的表名为test
,我们可以这样做:
select concat("SELECT * FROM test WHERE ", group_concat(concat(column_name, " IS NULL ") SEPARATOR "OR "))
into @sql
from information_schema.columns
where table_name = 'test'
and table_schema = 'foo';
这将生成并存储在 @sql
中,一个如下所示的查询:
SELECT *
FROM test
WHERE id IS NULL
OR col1 IS NULL
OR col2 IS NULL
OR col3 IS NULL
OR col4 IS NULL
OR col5 IS NULL
然后我们像这样准备声明:
prepare stmt from @sql
然后我们执行它来获取你的值
execute stmt
最后,我们取消分配语句。
deallocate prepare stmt;
这将是该序列的示例输出:
mysql> select * from test;
+----+------+------+------+------+------+
| id | col1 | col2 | col3 | col4 | col5 |
+----+------+------+------+------+------+
| 1 | 1 | 2 | 3 | 4 | 5 |
| 2 | 1 | 2 | 3 | 4 | 5 |
| 3 | 1 | 2 | 3 | 4 | 5 |
| 4 | 1 | 2 | 3 | 4 | NULL |
| 5 | NULL | 2 | 3 | 4 | 5 |
| 6 | 1 | NULL | 3 | 4 | 5 |
+----+------+------+------+------+------+
6 rows in set (0.00 sec)
mysql> select concat("SELECT * FROM test WHERE ", group_concat(concat(column_name, " IS NULL ") SEPARATOR "OR "))
-> into @sql
-> from information_schema.columns
-> where table_name = 'test'
-> and table_schema = 'foo';
Query OK, 1 row affected (0.01 sec)
mysql> prepare stmt from @sql;
Query OK, 0 rows affected (0.00 sec)
Statement prepared
mysql> execute stmt;
+----+------+------+------+------+------+
| id | col1 | col2 | col3 | col4 | col5 |
+----+------+------+------+------+------+
| 4 | 1 | 2 | 3 | 4 | NULL |
| 5 | NULL | 2 | 3 | 4 | 5 |
| 6 | 1 | NULL | 3 | 4 | 5 |
+----+------+------+------+------+------+
3 rows in set (0.00 sec)
mysql> deallocate prepare stmt;
Query OK, 0 rows affected (0.00 sec)
关于mysql - 在不提及列名的情况下查找具有空列的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29981593/