Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing mysql concat() in WHERE clause?
    primarykey
    data
    text
    <p>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, one at a time with </p> <pre><code> select * from table where first_name like '%$search_term%' or last_name like '%$search_term%'; </code></pre> <p>This works fine with single word search terms but the result set includes everyone with the name "Larry". But if someone enters a first name then a space, then a last name, I want a narrower search result. I've tried the following without success. </p> <pre><code> select * from table where first_name like '%$search_term%' or last_name like '%$search_term%' or concat_ws(' ',first_name,last_name) like '%$search_term%'; </code></pre> <p>Any advice?</p> <p><strong>EDIT:</strong> The name I'm testing with is "Larry Smith". The db stores "Larry" in the "first_name" column, and "Smith" in the "last_name" column. The data is clean, no extra spaces and the search term is trimmed left and right.</p> <p><strong>EDIT 2:</strong> I tried Robert Gamble's answer out this morning. His is very similar to what I was running last night. I can't explain it, but this morning it works. The only difference I can think of is that last night I ran the concat function as the third "or" segment of my search query (after looking through first_name and last_name). This morning I ran it as the last segment after looking through the above as well as addresses and business names. </p> <p>Does running a mysql function at the end of a query work better than in the middle?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload