mysql - 在不提及列名的情况下查找具有空列的行

标签 mysql

我想从我的数据库表中找到具有空列的行。
假设我的表有 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/

相关文章:

python - 使用 SQLAlchemy 无法在 Flask 应用程序中调用 BaseQuery 对象

php - 计算表中唯一数据的数量

mysql - 如何将列中的每个 NULL 值更新为零?

mysql - Sequelize 渴望获取多对多

mysql - 线程消息的 SQL 查询

mysql - 如何使用 Nodejs 和 MySQL 动态自动填充输入字段?

mysql - 如何根据大于或小于then的条件获取所有行?

php - 替换应该在 mysql 还是 php 中完成?

php登录数组问题

php - 如何在一个网页上连接多个 MySQL 数据库?