MYSQL获取所有列中仅包含NULL的所有行

时间:2016-03-12 14:38:33

标签: mysql select null

我有一个表,除了descrition列之外,所有列中只包含NULL的行。

    description | colA | colB
    -------------------------
    Peter       | bla  | NULL
    Frank       | NULL | NULL
    George      | NULL | blub

如何在没有明确命名的情况下选择所有列中包含NULL的所有行?

Pseudocode: SELECT ``decription`` WHERE all other columns are NULL应该归还弗兰克。我该如何做到这一点?

2 个答案:

答案 0 :(得分:1)

通过引用INFORMATION_SCHEMA并使用PREPARE语句,此处提供了一个解决方案,并提供了完整的演示。

解决方案是指:Select all columns except one in MySQL?

SQL:

-- data
create table t1(description char(20), colA char(20), colB char(20));
insert into t1 values
(    'Peter'       , 'bla', NULL),
(    'Frank'       , NULL , NULL),
(    'George'      , NULL , 'blub');
SELECT * FROM t1;

-- Query wanted
SET @sql = CONCAT(
    'SELECT description FROM t1 WHERE COALESCE(',
    (SELECT REPLACE(GROUP_CONCAT(COLUMN_NAME), 'description,', '') 
     FROM INFORMATION_SCHEMA.COLUMNS 
     WHERE TABLE_NAME = 't1' AND TABLE_SCHEMA = 'test'), 
    ') IS NULL');
PREPARE stmt1 FROM @sql;
EXECUTE stmt1;

输出:

mysql> SELECT * FROM t1;
+-------------+------+------+
| description | colA | colB |
+-------------+------+------+
| Peter       | bla  | NULL |
| Frank       | NULL | NULL |
| George      | NULL | blub |
+-------------+------+------+
3 rows in set (0.00 sec)

mysql>
mysql> SET @sql = CONCAT(
    -> 'SELECT description FROM t1 WHERE COALESCE(',
    -> (SELECT REPLACE(GROUP_CONCAT(COLUMN_NAME), 'description,', '')
    ->  FROM INFORMATION_SCHEMA.COLUMNS
    ->  WHERE TABLE_NAME = 't1' AND TABLE_SCHEMA = 'test'),
    -> ') IS NULL');
Query OK, 0 rows affected (0.00 sec)

mysql> PREPARE stmt1 FROM @sql;
Query OK, 0 rows affected (0.00 sec)
Statement prepared

mysql> EXECUTE stmt1;
+-------------+
| description |
+-------------+
| Frank       |
+-------------+
1 row in set (0.00 sec)

在PREPARE之前详细说明SET语句:

  1. SET将生成如下字符串。

    SELECT description FROM t1 WHERE COALESCE(<除description>之外的所有列的列表)是否为空

  2. 使用参考链接中的方法从INFORMATION_SCHEMA.COLUMNS查询。

  3.   

    要在您自己的环境中使用,您需要

         
        
    1. 将表名't1'更改为您自己的表名;

    2.   
    3. 将TABLE_SCHEMA'test'更改为您自己的数据库名称。

    4.   

答案 1 :(得分:-1)

SELECT TABLE FROM TABLE_NAME WHERE colA为NULL且colB为NULL