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

后端 未结 25 2222
灰色年华
灰色年华 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:49

    you're stuck with the

    WHERE something LIKE 'bla%'
    OR something LIKE '%foo%'
    OR something LIKE 'batz%'
    

    unless you populate a temp table (include the wild cards in with the data) and join like this:

    FROM YourTable                y
        INNER JOIN YourTempTable  t On y.something LIKE t.something
    

    try it out (using SQL Server syntax):

    declare @x table (x varchar(10))
    declare @y table (y varchar(10))
    
    insert @x values ('abcdefg')
    insert @x values ('abc')
    insert @x values ('mnop')
    
    insert @y values ('%abc%')
    insert @y values ('%b%')
    
    select distinct *
    FROM @x x
    WHERE x.x LIKE '%abc%' 
       or x.x LIKE '%b%'
    
    
    select distinct x.*  
    FROM @x             x
        INNER JOIN  @y  y On x.x LIKE y.y
    

    OUTPUT:

    x
    ----------
    abcdefg
    abc
    
    (2 row(s) affected)
    
    x
    ----------
    abc
    abcdefg
    
    (2 row(s) affected)
    

提交回复
热议问题