Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
628 views
in Technique[技术] by (71.8m points)

mysql - Combine two columns in SQL for WHERE clause

In my SQL, I am using the WHERE and LIKE clauses to perform a search. However, I need to perform the search on a combined value of two columns - first_name and last_name:

WHERE customers.first_name + customers.last_name LIKE '%John Smith%'

This doesn't work, but I wondered how I could do something along these lines?

I have tried to do seperate the search by the two columns, like so:

WHERE customers.first_name LIKE '%John Smith%' OR customers.last_name LIKE '%John Smith%'

But obviously that will not work, because the search query is the combined value of these two columns.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use the following:

WHERE CONCAT(customers.first_name, ' ', customers.last_name) LIKE '%John Smith%'

Note that in order for this to work as intended, first name and last name should be trimmed, i.e. they should not contain leading or trailing whitespaces. It's better to trim strings in PHP, before inserting to the database. But you can also incorporate trimming into your query like this:

WHERE CONCAT(TRIM(customers.first_name), ' ', TRIM(customers.last_name)) LIKE '%John Smith%'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...