Friday, May 9, 2008

MySQL - find only words in a field

This snippet here is pure gold! When making a keyword search, I searched high and low for a method to use MySQL to find an individual word.

I even asked my professor, who taught the databases course at Cal State San Marocs(a credible Computer Science department), and he is to be respected, for he knows a great deal about Computer Science. He told me he would get back to me, but either he didn't try to find the answer or he tried and couldn't figure it out!

Here's an example of the problem: suppose I want to search for a book title, which requires querying title fields in a table called 'Books'. Now suppose I want to find books with the word 'hot' in their title. But I don't want to return books that contain the words 'shot', 'hotel', 'thot', etc.

The key is to use the REGEXP operator. And there are a series of symbols you can use. I will post the site listing the symbols, but the main symbol you need to know is the [[:<:]] [[:>:]] symbols. This locates words in a field that either have nothing next to it or a space, comma, or period next to it. Observe:

SELECT * 
FROM books
WHERE title REGEXP '[[:<:]]hot[[:>:]]';


Wow, what a simple solution to such a long-sought and puzzling question. Here is the website for the other metacharacters. Also, I might add that after I found the answer, I never told my professor :).

No comments: