1

I am wondering if i can put something in my query which searches for a word within a string. For example, if i have a field named user_purchased, i want to query it and pull only records where the word 'dog' exists within the string.

I know i can do this using php like this

(!stristr($row['user_purchased'], 'dog'))

BUT, i'm wondering if i can do this in the query itself instead and that this will perhaps speed up performance.

Thanks in advance for help on this

3
  • Please be aware that all the answers you're getting involving LIKE '%foo%' or INSTR force a full scan. This will be slow if your table is big. They can not do an index lookup. Commented Oct 21, 2011 at 21:25
  • thanks what would i use instead if i wanted to maximize speed. my table is big so speed is an issue Commented Oct 21, 2011 at 21:32
  • if speed is critical, you need an indexing solution such as MySQL fulltext or Sphinx. Commented Oct 21, 2011 at 21:43

3 Answers 3

1

You can use LIKE:

WHERE your_col LIKE '%dog%'

If you want better performance you could look at a full text search. This uses a FULLTEXT index to quickly find the matching rows.

Sign up to request clarification or add additional context in comments.

2 Comments

thank you, this makes sense. how would i change this for searching for results that DID NOT have the word dog in them?
figure this out, use NOT LIKE
0

In MySql, you can use INSTR(str,substr)

Quote from the MySql manual at http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_instr

INSTR(str,substr)

Returns the position of the first occurrence of substring substr in string str. This is the same as the two-argument form of LOCATE(), except that the order of the arguments is reversed.

mysql> SELECT INSTR('foobarbar', 'bar');
        -> 4
mysql> SELECT INSTR('xbar', 'foobar');
        -> 0
This function is multi-byte safe, and is case sensitive only if at least one argument is a binary string.

Comments

0

SELECT * FROM table WHERE user_purchased LIKE '%dog%';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.