views:

2425

answers:

6

I would like to write an SQL query that searches for a keyword in a text field, but only if it is a "whole word match" (e.g. when I search for "rid", it should not match "arid", but it should match "a rid".

I am using MySQL.

Fortunately, performance is not critical in this application, and the database size and string size are both comfortably small, but I would prefer to do it in the SQL than in the PHP driving it.

+1  A: 
select blah blah blah
where column like 'rid %'
   or column like '% rid'
   or column like '% rid %'
   or column =    'rid'
paxdiablo
Depending on the situation, you should also be careful of punctuation. For instance, none of those would return 'rid.'
Goog
I think the query is not sufficient. What about some text like "rid," or "(rid)"?
Wen Q.
+1  A: 
select * from table where Locate('rid ', FieldToSearch) > 0 
      or Locate(' rid', FieldToSearch) > 0

This will handle finding rid where it is preceded or followed by a space, you could extend the approach to take account of .,?! and so on, not elegant but easy.

MrTelly
+1  A: 

This is the best answer I've come up myself with so far:

SELECT * FROM table 
WHERE keywords REGEXP '^rid[ $]' OR keywords REGEXP ' rid[ $]'

I would have simplified it to:

SELECT *
FROM table
WHERE keywords REGEXP '[^ ]rid[ $]'

but [^ ] has a special meaning of "NOT a space", rather than "line-beginning or space".

How does REGEXP compare to multiple LIKE conditions? (Not that performance matters in this app.)

Oddthinking
If you made it [ ^], I think the second would work. ^ is only "not" when it is the first character in a set, IIRC.
Travis Jensen
I wonder if SQL REGEXP has a "word boundary" field like Perl \b? That would handle spaces, punctuation, etc.
Andy White
@Andy, MySql uses [[:<:]] and [[:>:]] as word-boundary markers.
LukeH
@Oddthinking, Word-boundary markers are probably what you should be using. See my answer for an example.
LukeH
+7  A: 

You can use REGEXP and the [[:<:]] and [[:>:]] word-boundary markers:

SELECT *
FROM table 
WHERE keywords REGEXP '[[:<:]]rid[[:>:]]'
LukeH
How is it that this question has had 1k views, and yet your perfect answer has only had one upvote (from me)?
Oddthinking
A: 

code to retrieve all the rows and columns containing the word in textbox???

A: 

--BELOW QUERY RETURNS SYSDATE ONLY IF "WHOLEWORD" IS PRESENT SELECT SYSDATE FROM DUAL WHERE REGEXP_LIKE ('FIND WHOLEWORD ONLY FROM THIS STRING. WHOLEWORD1 SHOULD NOT BE SELECTED ','(\s)' || '(WHOLEWORD)' || '(\s)','i');

--BELOW QUERY DO NOT RETURN SINCE "WHOLEWORD" IS PRESENT SELECT SYSDATE FROM DUAL WHERE REGEXP_LIKE ('FIND WHOLEWORD_DUP ONLY FROM THIS STRING. WHOLEWORD1 SHOULD NOT BE SELECTED ','(\s)' || '(WHOLEWORD)' || '(\s)','i');

Regards Sandeep Gaadhe [email protected]

Sadneep Gaadhe