Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LIKE wildcard with multiple fields and spaces in MYSQL

I'm having some trouble searching for any similar match in two fields. For example I have a table with the values:

CAR MAKE   CAR MODEL
Ford       Mustang (Shelby)
Toyota     Corolla
Seat       Leon

etc etc.

I want to be able to get the result "Ford, Mustang (Shelby)" by searching for any of the following combinations:

  • Ford

  • Mustang

  • Shelby

  • Ford Mustang

    or any other combination.

Is this possible? I've had a good search but it's hard to find the search terms to describe what I mean.

like image 911
penpen Avatar asked Aug 20 '11 03:08

penpen


People also ask

Which is the multi character wildcard in MySQL?

Multiple Character Wildcards Whilst the underscore wildcard is often useful, a far more powerful wildcard is the multiple character percent sign (%) wildcard. The percent sign wildcard can be used to represent any number of characters in a value match.

How do I use multiple wildcards in SQL?

There are two wildcards used in conjunction with the LIKE operator. The percent sign represents zero, one or multiple characters. The underscore represents a single number or character. These symbols can be used in combinations.

What is like %% in SQL?

The LIKE operator is used in a WHERE clause to search for a specified pattern in a column. There are two wildcards often used in conjunction with the LIKE operator: The percent sign (%) represents zero, one, or multiple characters. The underscore sign (_) represents one, single character.

How do I create a multiple like condition in SQL?

OR product_name LIKE '__s%'); In the above code, we use the OR operator to specify multiple conditions using the OR operator. The resulting table should return: Only the records that match either of the specified conditions are returned.


2 Answers

Split your terms on whitespace and then, for each term, build a little bit of SQL like this:

car_make like '%x%' or car_model like '%x%'

Then join all of those with or to get your WHERE clause. So for "Shelby Ford", you'd end up with SQL like this:

select stuff
from cars
where car_make like '%Shelby%'
   or car_model like '%Shelby%'
   or car_make like '%Ford%'
   or car_model like '%Ford%'

If you need anything more complicated then investigate MySQL's full-text search capabilities.

like image 121
mu is too short Avatar answered Oct 20 '22 22:10

mu is too short


Give this a try:

SELECT Car_Make, Car_Model, CONCAT_WS(' ', Car_Make, Car_Model) as Make_Model 
FROM cars 
WHERE CONCAT_WS(' ', Car_Make, Car_Model) LIKE '%Ford Mustang%'

Not sure of the exact syntax since I'm not at home but something similar should work.

See also: Using mysql concat() in WHERE clause?

like image 27
Banjoe Avatar answered Oct 21 '22 00:10

Banjoe