2

If I search for LENA, I only want to get results where LENA is one word and not part of a word like Lenason or Anna-Lena or Malena

How do I write such a query, not

"select * from users where name like '%LENA%'"

What should it be instead?

1
  • I see you un-accepted my answer; what went wrong? Commented Sep 12, 2010 at 4:40

3 Answers 3

4

Use this one:

select * from users where name like '% LENA %' OR name like 'LENA %' OR name like '% LENA' OR name like 'LENA'

Try it, it will work, and too simple with 2 spaces at start and end. Its long but fast query. You can also use Full Text Search, Concat, Regex ... but for me, I like simple, just add some space before %.

However, you can try shorter but slower query:

SELECT * FROM users  WHERE name REGEXP '(^|\s+)LENA($|\s+)' 
Sign up to request clarification or add additional context in comments.

Comments

1

You could use REGEXP:

SELECT fields 
  FROM users
 WHERE name REGEXP '(^|\s+)LENA($|\s+)'

Comments

1

You might be better off looking into Full Text Search for this.

Otherwise I think you're stuck doing something like this

"select * from users WHERE CONCAT(' ',name, ' ') like '% LENA %'"

Which will be pretty inefficient as it requires a full table scan.

3 Comments

Full Text Search would do the trick, but your "something like" query will give identical results as the original (but with more cpu overhead).
@Bob - You were right that there was an issue with my query but not the one you were thinking of I think. I forgot that you needed to use CONCAT for string concatenation in MySQL rather than +. The reason for concatenating spaces is that names where lena is the first, last or only word wouldn't match the where clause name like '% LENA %' without this.
Looked up '%' in the MySQL manual and it also matches zero characters. This was the flaw in my logic.

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.