cpcdev
cpcdev

Reputation: 1222

SQL search columns separately with one combined keyword

I'm building a search form to search first and last names in a table:

Table structure:

Column 1 - First Name
Column 2 - Last Name

Here's my current query:

SELECT * 
FROM customers 
WHERE first_name LIKE '%" . $keyword . "%'" . " OR 
    last_name LIKE '%" . $keyword . "%'"

This works fine if I search a first name separately or a last name separately.

How can I modify the query to search both a first name and last name together as one keyword and also still be able to search a first and last name separately?

Example: "Joe Shmoe"

With the above query, if I search "Joe Shmoe" it does not return any results.

I tried this example but can't get it right.

Upvotes: 0

Views: 36

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1270493

Is this what you want?

SELECT c.*
FROM customers c
WHERE CONCAT_WS(' ', first_name, last_name) LIKE '%" . $keyword . "%'" . "

Upvotes: 3

Related Questions