Is it possible to use LIKE and IN for a WHERE statment?

后端 未结 4 1668
后悔当初
后悔当初 2020-12-06 17:47

I have a list of place names and would like to match them to records in a sql database the problem is the properties have reference numbers after there name. eg. \'Ballymena

相关标签:
4条回答
  • 2020-12-06 18:01

    you could use OR

    WHERE 
      dbo.[Places].[Name] LIKE 'Ballymena%' 
      OR dbo.[Places].[Name] LIKE 'Banger%'
    

    or split the string at the space, if the places.name is always in the same format.

    WHERE SUBSTRING(dbo.[Places].[Name], 1, CHARINDEX(dbo.[Places].[Name], ' ')) 
      IN ('Ballymena', 'Banger')
    

    This might decrease performance, because the database may be able to use indexes with like (if the wildcard is at the end you have even a better chance) but most probably not when using substring.

    0 讨论(0)
  • 2020-12-06 18:02

    No, but you can use OR instead:

    WHERE (dbo.[Places].[Name] LIKE 'Ballymena%' OR
           dbo.[Places].[Name] LIKE 'Banger%')
    
    0 讨论(0)
  • 2020-12-06 18:18

    well a simple solution would be using regular expression not sure how it's done in sql but probably something similiar to this

    WHERE dbo.[Places].[Name]  SIMILAR TO '(Banger|Ballymena)';
    

    or

    WHERE dbo.[Places].[Name] REGEXP_LIKE(dbo.[Places].[Name],'(Banger|Ballymena)');
    

    one of them should atleast work

    0 讨论(0)
  • 2020-12-06 18:22

    It's a common misconception that for the construct

    b IN (x, y, z)
    

    that (x, y, z) represents a set. It does not.

    Rather, it is merely syntactic sugar for

    (b = x OR b = y OR b = z)
    

    SQL has but one data structure: the table. If you want to query search text values as a set then put them into a table. Then you can JOIN your search text table to your Places table using LIKE in the JOIN condition e.g.

    WITH Places (Name)
         AS
         (
          SELECT Name
            FROM (
                  VALUES ('Ballymeade Country Club'), 
                         ('Ballymena Candles'), 
                         ('Bangers & Mash Cafe'), 
                         ('Bangebis')
                 ) AS Places (Name)
         ), 
         SearchText (search_text)
         AS
         (
          SELECT search_text
            FROM (
                  VALUES ('Ballymena'), 
                         ('Banger')
                 ) AS SearchText (search_text)
         )
    SELECT * 
      FROM Places AS P1
           LEFT OUTER JOIN SearchText AS S1
              ON P1.Name LIKE S1.search_text + '%';
    
    0 讨论(0)
提交回复
热议问题