Search code examples
mysqlsqlsql-like

MySQL Select Like


I've got a field in my table for tags on some content, separated by spaces, and at the moment I'm using:

SELECT * FROM content WHERE tags LIKE '%$selectedtag%'"

But if the selected tag is elephant, it will select content tagged with bigelephant and elephantblah etc...

How do I get it to just select what I want precisely?


Solution

  • SELECT * FROM content WHERE tags RLIKE '[[:<:]]elephant[[:>:]]'
    

    If your table is MyISAM, you can use this:

    SELECT * FROM content WHERE MATCH(tags) AGAINST ('+elephant' IN BOOLEAN MODE)
    

    , which can be drastically improved by creating a FULLTEXT index on it:

    CREATE FULLTEXT INDEX ix_content_tags ON content (tags)
    

    , but will work even without the index.

    For this to work, you should adjust @@ft_min_wold_len to index tags less than 4 characters long if you have any.