mysql: find rows which have a field that is a substring of “string”

前端 未结 4 737
猫巷女王i
猫巷女王i 2021-01-23 10:21

is there a way to write an sql query that finds all rows where the field value is a substring of a given string.

Example:

table names

Name      |      N         


        
相关标签:
4条回答
  • 2021-01-23 10:47

    If one of Name or Nickname has to be found within the text use

    SELECT *
    FROM names
    WHERE instr("who is Rohit", Name) > 0
       OR instr("who is Rohit", Nickname) > 0
    

    No index can be used for that, so it might take long for large tables.

    0 讨论(0)
  • 2021-01-23 11:06
    SELECT * FROM names WHERE INSTR(Nickname,Name) > 0;
    

    or, equivalently:

    SELECT * FROM names WHERE LOCATE(Name,Nickname) > 0;
    
    0 讨论(0)
  • 2021-01-23 11:13

    One problem with all these approaches is your indexes go right out the window. You'll have to do a table scan for each and every row, which means your performance will only get worse and worse as the table size grows.

    I'd rethink this approach if your table is going to be large. Maybe you need a indexed searcher like Lucene.

    0 讨论(0)
  • 2021-01-23 11:13

    You can also reverse the LIKE condition.

    select * from names where "who is rohit" LIKE  CONCAT('%', Name, '%');
    

    Note, this probably isn't any faster than instr("who is Rohit", Name) but it may be.

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