Using mysql concat() in WHERE clause?

后端 未结 7 2019
旧巷少年郎
旧巷少年郎 2020-11-29 00:59

I would like to search my table having a column of first names and a column of last names. I currently accept a search term from a field and compare it against both columns

7条回答
  •  情话喂你
    2020-11-29 01:38

    There's a few things that could get in the way - is your data clean?

    It could be that you have spaces at the end of the first name field, which then means you have two spaces between the firstname and lastname when you concat them? Using trim(first_name)/trim(last_name) will fix this - although the real fix is to update your data.

    You could also this to match where two words both occur but not necessarily together (assuming you are in php - which the $search_term variable suggests you are)

    $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);
    

提交回复
热议问题