MySQL: Look for the same string in multiple columns

11,162

Simple workaround:

SELECT * 
FROM projects 
WHERE 
    CONCAT(category,name,description,keywords,type) LIKE '%query%' 
ORDER BY name ASC;

You can add separators between columns if needed:

SELECT * 
FROM projects 
WHERE 
    CONCAT(category,"|",name,"|",description,"|",keywords,"|",type) LIKE '%query%' 
ORDER BY name ASC;

You can also use a fulltext search (you need to create a fulltext index as described here: How do FULLTEXT INDEXES on multiple columns work?)

SELECT *, MATCH (category,name,description,keywords,type) AGAINST ('query') AS score FROM projects WHERE MATCH (category,name,description,keywords,type) AGAINST ('query');
Share:
11,162

Related videos on Youtube

mreethmandir
Author by

mreethmandir

Updated on August 28, 2022

Comments

  • mreethmandir
    mreethmandir over 1 year

    I am trying to make a search-page-like function. I want to make a query to look for "query" in "ColumnA" and "ColumnB" and "ColumnC" and "ColumnD". And select the rows which has the word/phrase "query" in any of those columns. This appears to work:

       SELECT * FROM projects
       WHERE 
       category LIKE '%query%' OR
       name LIKE '%query%' OR 
       description LIKE '%query%'OR 
       keywords LIKE '%query%' OR 
       'type' LIKE '%query%'  
       ORDER BY name ASC   
    

    But it is lengthy. Is there any easier or more efficient way of doing this?

  • Paul Spiegel
    Paul Spiegel over 4 years
    You can use CONCAT_WS('|', category, name, ...) for your second query. I would even use it for the first query with an empty separator, because CONCAT_WS() will ignore NULL columns, while CONCAT() will return NULL if only one column is NULL.