1

I have a user table with columns named first_name and last_name.

SELECT * 
    FROM users 
WHERE first_name LIKE '%keywords%' 
    OR last_name LIKE '%keywords%'

Using the above, if I search for "John" or for "Doe" I'll get a hit.

But if I search for "John Doe" I will get 0 results. How can I search MySQL in a way that will match "first_name last_name" rather than just one or the other?

2
  • Are you limited to only using one variable? Commented Feb 3, 2010 at 3:14
  • The variable is input from a search field, so it may be just one word or it may be two (first and last name). Commented Feb 10, 2010 at 15:00

3 Answers 3

1

One solution is to split the keywords in your application, and then build the query as follows:

-- Split "John Doe" -> "John", "Doe"

SELECT * FROM users WHERE
(
    (
         first_name LIKE '%keyword_1%' OR
         last_name LIKE '%keyword_1%'
    )
    AND
    (
         first_name LIKE '%keyword_2%' OR
         last_name LIKE '%keyword_2%'
    )
)

The above would also match "Doe Joe", not just "Joe Doe". This will get bigger if you are searching into more columns, as you will have to add an "AND block" for each keyword.

In addition, this comes with a big performance cost, since such a query is unable to use indexes on first_name and last_name, if there are any. A better approach would be to use Full Text indexing.

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

Comments

0

Try:

SELECT * FROM users WHERE CONCAT(first_name, ' ', last_name) LIKE '%keywords%';

1 Comment

Good, but won't be able to use an index if one exists for first_name or last_name columns, in addition to using LIKE with a wildcard on the lefthand side.
0

Have you tried using full-text indexing?

2 Comments

Ehm - why do you provide the exact same link @Daniel Vassallo posted maybe 4 cm above your answer (if you sort by oldest, a bit further down if you sort by newest) six days before?
I think I must have missed that, after @Daniel Vassallo started off his answer in a quite different way.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.