Is there a combination of “LIKE” and “IN” in SQL?

后端 未结 25 1954
灰色年华
灰色年华 2020-11-22 03:08

In SQL I (sadly) often have to use \"LIKE\" conditions due to databases that violate nearly every rule of normalization. I can\'t change that right now. But tha

25条回答
  •  一个人的身影
    2020-11-22 03:56

    I'm working with SQl Server and Oracle here but I'm interested if this is possible in any RDBMS at all.

    Teradata supports LIKE ALL/ANY syntax:

    ALL every string in the list.
    ANY any string in the list.

    ┌──────────────────────────────┬────────────────────────────────────┐
    │      THIS expression …       │ IS equivalent to this expression … │
    ├──────────────────────────────┼────────────────────────────────────┤
    │ x LIKE ALL ('A%','%B','%C%') │ x LIKE 'A%'                        │
    │                              │ AND x LIKE '%B'                    │
    │                              │ AND x LIKE '%C%'                   │
    │                              │                                    │
    │ x LIKE ANY ('A%','%B','%C%') │ x LIKE 'A%'                        │
    │                              │ OR x LIKE '%B'                     │
    │                              │ OR x LIKE '%C%'                    │
    └──────────────────────────────┴────────────────────────────────────┘
    

    EDIT:

    jOOQ version 3.12.0 supports that syntax:

    Add synthetic [NOT] LIKE ANY and [NOT] LIKE ALL operators

    A lot of times, SQL users would like to be able to combine LIKE and IN predicates, as in:

    SELECT *
    FROM customer
    WHERE last_name [ NOT ] LIKE ANY ('A%', 'E%') [ ESCAPE '!' ]
    

    The workaround is to manually expand the predicate to the equivalent

    SELECT *
    FROM customer
    WHERE last_name LIKE 'A%'
    OR last_name LIKE 'E%'
    

    jOOQ could support such a synthetic predicate out of the box.


    PostgreSQL LIKE/ILIKE ANY (ARRAY[]):

    SELECT *
    FROM t
    WHERE c LIKE ANY (ARRAY['A%', '%B']);
    
    SELECT *
    FROM t
    WHERE c LIKE ANY ('{"Do%", "%at"}');
    

    db<>fiddle demo


    Snowflake also supports LIKE ANY/LIKE ALL matching:

    LIKE ANY/ALL

    Allows case-sensitive matching of strings based on comparison with one or more patterns.

     LIKE ANY ( [,  ... ] ) [ ESCAPE  ]
    

    Example:

    SELECT * 
    FROM like_example 
    WHERE subject LIKE ANY ('%Jo%oe%','T%e')
    -- WHERE subject LIKE ALL ('%Jo%oe%','J%e')
    

提交回复
热议问题