20

I have a customer table with two columns first_name and last_name.

How can I use LIKE in a query being able to get data from both columns at same time?

For instance:

SELECT CONCAT(first_name, ' ', last_name) as 'full_name' 
FROM customer WHERE full_name LIKE 'John D%'

I've tried this and it tells me full_name column doesn't exist.

RedDragon
  • 2,080
  • 2
  • 26
  • 42
  • [Full Text Search](http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html) is the most efficient means in SQL to do what you want. – OMG Ponies Aug 11 '11 at 14:15
  • @OMG As I could change the table and the data insertion, I created a new indexed column full_name and used it instead due to performance issues mentioned in the answers. – RedDragon Aug 11 '11 at 15:20

5 Answers5

36
SELECT CONCAT(first_name, ' ', last_name) as 'full_name' 
FROM customer WHERE CONCAT(first_name, ' ', last_name) LIKE 'John D%'
Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662
6

You are almost there

SELECT * 
FROM customer 
WHERE CONCAT(first_name, ' ', last_name) LIKE 'John D%'

Note: this may not have very good performance. You might want to consider full text search.

Nivas
  • 18,126
  • 4
  • 62
  • 76
4

Use HAVING instead of WHERE:

SELECT CONCAT(first_name, ' ', last_name) as 'full_name' 
   FROM customer HAVING full_name LIKE 'John D%'
nobody
  • 10,599
  • 4
  • 26
  • 43
0
SELECT * 
FROM customer 
WHERE CONCAT(first_name, ' ', last_name) LIKE 'John D%' 

might be very slow but that won't matter if your database is quite small. When using CONCAT make sure the Collation is same for both the column names or else it will fetch you an error.

Below is a statement for when I want my LIKE statement to work for both category name and course name. I check for cat_id in both tables so that I can have an idea which course belongs to which category.

SELECT * FROM courses a INNER JOIN categories b ON a.cat_id=b.cat_id 
WHERE CONCAT(b.cat_name,' ',a.course_name)
LIKE :name ORDER BY b.cat_id

:name is placeholder (PDO)

Bob Gilmore
  • 12,608
  • 13
  • 46
  • 53
user2634882
  • 179
  • 7
0

I don't have MySql at hand, but can't u do something like the code below?

SELECT CONCAT(first_name, ' ', last_name) as 'full_name' 
FROM customer WHERE CONCAT(first_name, ' ', last_name) LIKE 'John D%'

Disclaimer: THIS COULD BE VERY SLOW!!!

Kralizek
  • 1,999
  • 1
  • 28
  • 47