Can I make WHERE col LIKE '%' select NULL values too?

后端 未结 5 1757
我在风中等你
我在风中等你 2021-02-04 13:25

I am trying to make a selection from a MySQL database using the syntax WHERE col LIKE \'%\' but I want to select even NULL values with that query. Is t

相关标签:
5条回答
  • 2021-02-04 14:14

    Use COALESCE instead of IFNULL if you want to use it with java createQuery

    WHERE COALESCE (xxx, '') LIKE '%'
    
    0 讨论(0)
  • 2021-02-04 14:16

    If you want column1 LIKE '%' and want column1 IS NULL, why not just drop the WHERE clause?

    Try:

    SELECT * FROM TABLE;
    

    Here's what I tried:

    mysql> create table foo (a char(30));
    Query OK, 0 rows affected (0.02 sec)
    
    mysql> insert into foo values ( '' );
    Query OK, 1 row affected (0.01 sec)
    
    mysql> insert into foo values ( NULL );
    Query OK, 1 row affected (0.00 sec)
    
    mysql> select * from foo;
    +------+
    | a    |
    +------+
    |      |
    | NULL |
    +------+
    2 rows in set (0.00 sec)
    
    mysql> select * from foo where a like '%' or a is null;
    +------+
    | a    |
    +------+
    |      |
    | NULL |
    +------+
    2 rows in set (0.00 sec)
    
    mysql> select * from foo where ifnull (a, 1) like '%';
    +------+
    | a    |
    +------+
    |      |
    | NULL |
    +------+
    2 rows in set (0.00 sec)
    
    mysql> 
    

    After all, IFNULL(column1, 1) LIKE '%' is effectively a NO-OP ...

    0 讨论(0)
  • 2021-02-04 14:19

    This statement returns all rows EXCEPT rows which have NULL in column1

    SELECT * FROM table WHERE column1 LIKE '%'
    

    To get all rows including rows with NULL in column1, use this:

    SELECT * FROM table WHERE IFNULL(column1,1) LIKE '%'
    

    from the MySQL documentation:

    IFNULL(expr1,expr2)

    If expr1 is not NULL, IFNULL() returns expr1; otherwise it returns expr2. IFNULL() returns a numeric or string value, depending on the context in which it is used.

    There's one caveat however: If you have an index on column1, it won't be used in this query, so things could get slow in larger tables...

    0 讨论(0)
  • 2021-02-04 14:22

    Use the IFNULL operator

    WHERE IFNULL(xxx, '') LIKE '%'
    
    0 讨论(0)
  • 2021-02-04 14:30
    SELECT * FROM table WHERE (job LIKE '%' OR job IS NULL)
    
    0 讨论(0)
提交回复
热议问题