Using mysql concat() in WHERE clause?

后端 未结 7 2002
旧巷少年郎
旧巷少年郎 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:35

    you can do that (work in mysql) probably other SQL too.. just try this:

    select * from table where concat(' ',first_name,last_name) 
        like '%$search_term%';
    
    0 讨论(0)
  • 2020-11-29 01:37

    You can try this:

    select * FROM table where (concat(first_name, ' ', last_name)) = $search_term;
    
    0 讨论(0)
  • 2020-11-29 01:38

    What you have should work but can be reduced to:

    select * from table where concat_ws(' ',first_name,last_name) 
    like '%$search_term%';
    

    Can you provide an example name and search term where this doesn't work?

    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2020-11-29 01:44

    To Luc:

    I agree with your answer, although I would like to add that UPPER only works on non-binary elements. If you are working with say an AGE column (or anything numeric) you will need to perform a CAST conversion to make the UPPER function work correctly.

    SELECT * FROM table WHERE UPPER(CONCAT_WS(' ', first_name, last_name, CAST(age AS CHAR)) LIKE UPPER('%$search_term%');
    

    Forgive me for not responding to Luc's answer directly but for the life of me I could not figure out how to do that. If an admin can move my post, please do so.

    0 讨论(0)
  • 2020-11-29 01:53
    SELECT *,concat_ws(' ',first_name,last_name) AS whole_name FROM users HAVING whole_name LIKE '%$search_term%'
    

    ...is probably what you want.

    0 讨论(0)
提交回复
热议问题