views:

240

answers:

3

i want to check if a string contains a field value as a substring or not.

select * from mytable where instr("mystring", column_name);

but this does not search on word boundaries.

select * from mytable where instr("mystring", concat('[[:<:]]',column_name,'[[:>:]]');

does not work either. how to correct this?

A: 

If you don't need the return value of the instr use like instead

select * from mytable where column_name like '%mystring%';
Pentium10
this won't search on word boundaries right.
iamrohitbanga
can you tell me an example for your content
Pentium10
http://stackoverflow.com/questions/2123738/mysql-find-rows-which-have-a-field-that-is-a-substring-of-string/2123783#2123783
iamrohitbanga
+1  A: 

You can do this using the REGEXP operator:

SELECT * FROM mytable WHERE 'mystring' REGEXP CONCAT('[[:<:]]', column_name, '[[:>:]]');

Note, however, that this is slow. You might be best off using the MySQL's FULLTEXT search feature if you care about words. Or do a normal InStr() check then filter the results.

Max Shawabkeh
cool, it works. i'll consider full index search later. right now it is a prototype. it seems we cannot specify word boundaries with instr(). right?full text search in natural language was giving partial matches also, which would need to be fixed.
iamrohitbanga
Yes, `InStr()` simply searches for a substring.
Max Shawabkeh
+1: Regexp is the way to go.
Peter Lang
A: 

As already discussed in the question you asked yesterday, no indexes can be used and performance is going to be bad, but this could work:

select *
from mytable
where 'mystring' = column_name                           -- exact match
   or 'mystring' like concat('% ', column_name)          -- word at the end
   or 'mystring' like concat(column_name, ' %')          -- word at beginning
   or 'mystring' like concat('% ', column_name, ' %')    -- word in the middle
Peter Lang
this would match if the column_name string occurs as a substring of a word. it should match on word boundaries only.
iamrohitbanga
No, it would not. It will match only if the query is surrounded by spaces/start/end. It won't match it when it's followed by a period though.
Max Shawabkeh
it is matching `mystringxyz` which is what i don't want. i tested it.
iamrohitbanga
Did you paste the exact query with all spaces? Could you please try which one matches by trying the conditions separately?
Peter Lang
last one matches.
iamrohitbanga
why would index searches not work. i could not get your point yesterday also.
iamrohitbanga
@iamrohitbanga: You are right, actually. The matches should be `concat('% ', col)` (at end), `concat(col, ' %')` (at start) and `concat('% ', col, ' %')` (middle).
Max Shawabkeh
ok, for now i'll use regexp solution.
iamrohitbanga
@Max S.: Thanks, don't know what I was thinking :) Corrected now.
Peter Lang