mysql: instr specify word boundaries

2019-08-29 19:43发布

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?

3条回答
爷的心禁止访问
2楼-- · 2019-08-29 20:01

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.

查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-08-29 20:08

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
查看更多
beautiful°
4楼-- · 2019-08-29 20:20

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

select * from mytable where column_name like '%mystring%';
查看更多
登录 后发表回答