Using OR in LIKE Query in MySQL to compare multiple fields

前端 未结 2 1405
猫巷女王i
猫巷女王i 2020-12-05 18:47

I always thought that you could use OR in a LIKE statment to query things in MySQL. So, if I wanted to compare multiple fields in a row to 1 keywo

相关标签:
2条回答
  • 2020-12-05 19:27

    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.

    0 讨论(0)
  • 2020-12-05 19:31

    Use this::

    SELECT * FROM MyTable WHERE (Column1 LIKE '%keyword1%' OR Column2 LIKE 
    '%keyword1%') AND (Column1 LIKE '%keyword2%' OR Column2 LIKE '%keyword2%');
    
    0 讨论(0)
提交回复
热议问题