Search code examples
phpmysqlselectsql-like

Order of LIKE clause in query when wanting to use multiple terms


I have the query

SELECT * FROM images WHERE tags LIKE '%example%hello%'

I would like the database to select rows which have 'example' and 'hello' in the 'tags' column in any order, as in:

A row with 'hello, test, example', also 'example, hello, test' or any other variation of this order. Is this possible, even without using LIKE? The rows must all contain everything specified with LIKE.

EDIT: Such as, when I provide 'example' and 'hello' in the query, rows returned must contain both 'example' and 'hello'.


Solution

  • You could try a simple OR for a quick solution:

    SELECT * FROM images WHERE tags LIKE '%example%' OR tags LIKE '%hello%'
    

    EDIT

    To address your edit, you can use AND instead:

    SELECT * FROM images WHERE tags LIKE '%example%' AND tags LIKE '%hello%'