Using OR in LIKE Query in MySQL to compare multiple fields

The closest to the syntax you are desiring is:

SELECT * FROM MyTable
WHERE (CONCAT(Column1, Column2) LIKE '%keyword1%')
AND (CONCAT(Column1, Column2) LIKE '%keyword2%')

Note: that the "%" at the start of your search string precludes the use of indexes. If there are any large number of records to search, it would be best to rethink the implementation.

If you cannot guarantee that each column is not NULL, then use CONCAT_WS instead:

SELECT * FROM MyTable
WHERE (CONCAT_WS("-", Column1, Column2) LIKE '%keyword1%')
AND (CONCAT_WS("-", Column1, Column2) LIKE '%keyword2%')

This CONCAT_WS solution also has the possible benefit of assuring that matches of your "keyword" where in only in Column1 OR Column2, if you select a separator character that is never present in your keywords.


Use this::

SELECT * FROM MyTable WHERE (Column1 LIKE '%keyword1%' OR Column2 LIKE 
'%keyword1%') AND (Column1 LIKE '%keyword2%' OR Column2 LIKE '%keyword2%');

Tags:

Mysql

Sql Like