WHERE all IS NOT NULL

后端 未结 9 1811
暖寄归人
暖寄归人 2020-12-10 10:38

How can I run a MySQL query that selects everything that is not null? It would be something like

SELECT * FROM schedule WHERE ((all)) IS NOT NULL


        
相关标签:
9条回答
  • 2020-12-10 11:22

    I would not do this, but to replace someone else's horrible idea., especially do not do this -- this is what they suggested:

    SELECT *
      FROM SCHEDULE
     WHERE ID || FOO || BAR IS NOT NULL;
    

    Don't do this either, but at least it isn't as bad...

    SELECT *
      FROM SCHEDULE
    WHERE coalesce(ID, FOO, BAR) IS NOT NULL;
    

    This at least works on other versions of SQL, and some compilers will expand it to a series of IS NOT NULL.

    Just do what the accepted answer says

    0 讨论(0)
  • 2020-12-10 11:26

    You can concatenate the fields in order to write only a where-condition:

    SELECT *
      FROM SCHEDULE
     WHERE ID || FOO || BAR IS NOT NULL;
    
    0 讨论(0)
  • 2020-12-10 11:26

    You need to get a list of the columns of your table, by looking at the information_schema database.

    Let's suppose that your database is called mydata and your table in question is named mytable. You can get the list of the table's nullable columns by issuing the following statement:

    SELECT `COLUMN_NAME`
    FROM `information_schema`.`COLUMNS`
    WHERE `TABLE_SCHEMA` = 'mydata'
        AND `TABLE_NAME` = 'mytable'
        AND `IS_NULLABLE` = 'YES'
    

    Our final query will look like this:

    SELECT * FROM `mydata`.`mytable`
    WHERE CONCAT(<list of columns>) IS NOT NULL
    

    All we are missing now is the list of nullable columns, comma-separated. We're going to use the GROUP_CONCAT function to produce the final statement, which we will execute like this:

    SET @query = CONCAT(
        'SELECT * FROM `mydata`.`mytable` WHERE CONCAT(',
        (SELECT GROUP_CONCAT(COLUMN_NAME)
            FROM `information_schema`.`COLUMNS`
            WHERE `TABLE_SCHEMA` = 'mydata' AND
            `TABLE_NAME` = 'mytable'
            AND `IS_NULLABLE` = 'YES'),
        ') IS NOT NULL');
    
    PREPARE stmt_name FROM @query;
    
    EXECUTE stmt_name;
    

    References:

    http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat

    http://dev.mysql.com/tech-resources/articles/4.1/prepared-statements.html

    0 讨论(0)
提交回复
热议问题