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

后端 未结 4 1692
后悔当初
后悔当初 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: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 + '%';
    

提交回复
热议问题