我想找到我的db表中有空列的行 假设我的表有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)
如何编写此查询以选择具有空/空值的行(在任何列中)。
答案 0 :(得分:1)
表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)
答案 1 :(得分:0)
是的,你可以做,但你需要使用PL / SQL。你可以吗???