views:

34

answers:

2

I have some code that builds SQL queries to perform a lenient, catch-all kind of search on a potentially large table that loooks a little like this

// $find_array derived from search string with space or comma used as a delimiter
foreach($find_array as $term){
    $clauses[]="(  
        OR last_name SOUNDS LIKE '$term'
        OR first_name SOUNDS LIKE '$term' 
        OR first_name LIKE '%$term%' 
        OR email SOUNDS LIKE '$term' 
        OR email LIKE '%$term%'                     

               [etc...]

        OR city LIKE '%$term%' 
        OR company SOUNDS LIKE '$term' 
        OR company LIKE '%$term%' 
    )";
}

This may be a very wrong way of doing it, but I guess it made sense at the time.

Looking at the queries this produces, though -- they are, of course, even with limits on search terms, about a mile long and littered with ORs. Is this a terrible crime of some sort -- in terms of performance or otherwise?

Is it better to use the IN clause whenever possible?

+2  A: 

I wouldn't say it's a crime; if that's what you want to find, that's what your query has to do. Since you are looking for embedded text, you may wish to consider TEXT columns and FULLTEXT indexes. I would provide a pointer to the documentation but the MySQL website appears to have been taken over by Oracle marketing droids and I can't find anything worthwhile on it.

Brian Hooper
+1  A: 

IMHO, there is nothing wrong with it.

.
Even the two major MySQL Admin apps, PHPMyAdmin and Adminer (formerly PHPMinAdmin) use exactly the same way to create a search / catch-all search. See following screenshot:
.

alt text

shamittomar