I have the following query:
SELECT * FROM table
WHERE tags LIKE '%$search%'
AND tags NOT LIKE '% $search%'
AND tags NOT LIKE '%$search %'
Basically it’s searching for for all terms that match unless there’s a space before or after the search term.
So if I searched for "novel", the terms "graphic novel" or "novel romantic" will not show up.
This seems like a costly query, so I was wondering if there is a more efficient way to do this. Thanks!
A regular expression match will make the query shorter )prettier is a matter of the observer), but most definitely not more efficient.
Looking at your comment to Sashi Kant, am I right do deduce the text on which you are searching is a comma delimited set of attributes? You wrote:
big,novel,graphic novel. Is it always like that?If so, then, again, still not efficient but nevertheless easier to manage, is to write
What’s shared between your solution, a regex solution and the
FIND_IN_SETsolution is that neither can utilize any index on thetagscolumn. All queries are using some sort of function over the column, and that negates the usage af an index.If you want performance, and data format is as I think it is, then you may want to normalize the table. Create a new table like
known_tag:(pick your own data types)
And then a many-to-many connecting table, like:
And finally, work your query like this:
This type of query will use the proper indexes and be more efficient on large tables.