Performing a LIKE comparison on an INT field

前端 未结 2 1509
感动是毒
感动是毒 2020-12-09 15:49

I\'m fairly new to SQL and I was trying to get a full list of products that match a user input of a productID. Something like:

SELECT ProductID, ProductName          


        
相关标签:
2条回答
  • 2020-12-09 16:36

    You can CAST the field to a string:

     ... WHERE CAST(ProductID as CHAR) LIKE '%15%'
    

    this is very bad for performance, as mySQL can't make use of any indexes it's created for the INT column. But then, LIKE is always slow, even when done on a varchar field: There's no way to have an index that speeds up a LIKE query.

    It might be worth having a second varchar column that mirrors the int column's values and doing the LIKE on that one - you'd have to benchmark to find out whether it'll do any good.

    0 讨论(0)
  • 2020-12-09 16:39

    You can convert int to string using CONVERT(ProductID, CHAR(16)) AS ProductID and then use LIKE. So in your case it would be

    SELECT ProductID, ProductName FROM Products
    WHERE CONVERT(ProductID, CHAR(16)) LIKE '%15%'
    

    You should remember that the query will make a full table scan without any support from indices. As a result it will be really expensive and time consuming.

    0 讨论(0)
提交回复
热议问题