问题
I have a database table which has a field firstname and a field lastname. I'm trying to implement an any-word search system using a search box where if let's say that we have a user named John Stanley Smith in the database (where firstname = John Stanley and lastname = Smith), I want to be able to return John Stanley Smith if the user types any of the following:
1- Any letter which is part of John Stanley Smith (j, s, l, e, y, m, etc...)
2- Any word which is part of John Stanley Smith
3- Any combination of words (in any order) which is part of John Stanley Smith, meaning that, if the user enters either John Stanley or John Smith or Stanley Smith or Stanley John (you get the idea) etc... I want to be able to find John Stanley Smith.
I know I can do this using the MySQL Fulltext Search feature, but if I do, point number one will not work (because the MySQL fulltext search feature only matches whole words, not substrings within a string). Also, there is a minimum number of words required for the search to be performed (set by the min_word_len constant). So, I really want to do this using LIKE %.
Thank you
回答1:
I might have misunderstood but have you considered just doing this:
SELECT * FROM customer WHERE
CONCAT(firstname, " ", lastname) LIKE '%$pattern%'
if the user enters more than one word, separated by whitespaces, simple split the string into words and modify the query to
SELECT * FROM customer WHERE
CONCAT(firstname, " ", lastname) LIKE '%$word1%'
OR CONCAT(firstname, " ", lastname) LIKE '%$word2%'
OR CONCAT(firstname, " ", lastname) LIKE '%$word3%'
...
回答2:
Hope this helps
$whereclauses=array();
$terms = explode(' ', $search_term);
foreach ($terms as $term) {
$term = mysql_real_escape_string($term);
$whereclauses[] = "CONCAT(first_name, ' ', last_name) LIKE '%$term%'";
}
$sql = "select * from table where";
$sql .= implode(' and ', $whereclauses);
来源:https://stackoverflow.com/questions/9406200/any-word-search-using-like