Reputation: 63
I trying to search a MySQL database using PHP, The search works fine but I'm looking for a little help with wildcards:
The data in the field (Model) I am searching is: "A4" (215 results)
My search string is:
SELECT * FROM `temp_comp`.`mvl` WHERE `Model` LIKE '%A4 Avant%'
Is there a way I can still search 'A4 Avant' but this will return any fields that contain 'A4' or 'Avant'
The search term is taken from a csv file so I wanted to try and do this without having to split the two words first and search for 'A4' and/or 'Avant', I have tried the following but get no results:
SELECT * FROM `temp_comp`.`mvl` WHERE `Model` LIKE '%A4%Avant%'
As you may have guessed this is not my normal field so any help would be very much appreciated.
Upvotes: 6
Views: 21928
Reputation: 76537
SELECT * FROM temp_comp.mvl WHERE (Model LIKE '%A4%') OR (Model LIKE '%Avant%')
If you want to avoid splitting up the test you can use a regexp:
SELECT * FROM temp_comp.mvl WHERE Model REGEXP 'A4|Avant' <<-- Either '%A4% or %Avant%
SELECT * FROM temp_comp.mvl WHERE Model REGEXP 'A4*Avant' <<-- '%A4%Avant%
See the reference
Upvotes: 11
Reputation: 5582
Here's how you can achieve this.
Modify your query like this:
SELECT * FROM `temp_comp`.`mvl` WHERE `Model` LIKE '%A4%' AND Model LIKE '%Avant%'
The above example will look for elements of the search term in the query in such a manner that they should all be present in the record. And if you want to search for records with either of the search terms, you can replace the word AND with OR and it does the job.
And ideally, you would follow these steps to prepare for the query:
Upvotes: 0
Reputation: 5579
MySQL doesn't have a built-in way to split strings in a query. Splitting them beforehand and then adding n predicates to the where clause is trivial.
SELECT * FROM `temp_comp`.`mvl`
WHERE `Model` LIKE '%A4%' OR `Model` LIKE '%Avant%';
Upvotes: 0