I have a string, like Elton 1999
, and a MySql table with 4 fields :
table(id, name, surname, year)
I have to check if, joining these fields as "single field", it contains all the words of my string.
I mean :
1 Elton John 1999 -> must return the record 2 Elton Peter 1999 -> must return the record 3 Paris Elton 1999 -> must return the record 4 Elto John 1999 -> must not return the record 5 Elton Pierre 2000 -> must not return the record
Can I do it directly with MySql or I need first to get all the records and than parse them on server side? (on PHP, in my case)
P.S. The same result must begin if my string is 1999 Elton, so the order of my words doesnt matter...
As long as your input strings are consistently formatted, you should be able to join the fields together using CONCAT_WS() with a space as the separator and compare them to your input string when querying.
SELECT * FROM myTbl WHERE CONCAT(name, surname, year) LIKE '%ELTON%1999'
or
SELECT * FROM myTbl WHERE CONCAT_WS(' ', name, surname, year) LIKE '%ELTON%1999'
to add a space between each of the fields. Thx majic bunnie.
Update: Well, if you want to search for possible matches on any column with a string of values in any order, then you could explode your string by space and search each word individually. See if this works
$query = "SELECT * FROM myTbl";
if(!empty($searchString)){
$query .= " WHERE ";
$arr = explode(' ', $searchString);
foreach($arr as $word)
$fields[] = "CONCAT_WS(' ', name, surname, year) LIKE %$word%";
$query .= implode(" AND ", $fields);
}
PS - I recently learned this query building technique from @yahyaE here :)