Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: Look for the same string in multiple columns

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?

like image 688
mreethmandir Avatar asked Nov 30 '13 14:11

mreethmandir


People also ask

How do I query multiple columns in SQL?

To select multiple columns from a table, simply separate the column names with commas! For example, this query selects two columns, name and birthdate , from the people table: SELECT name, birthdate FROM people; Sometimes, you may want to select all columns from a table.

How do I match a string in MySQL?

STRCMP() function in MySQL is used to compare two strings. If both of the strings are same then it returns 0, if the first argument is smaller than the second according to the defined order it returns -1 and it returns 1 when the second one is smaller the first one.

How use multiple columns in SQL with like?

multiple like statements can not be used with or directly. You have to use column name for each like statement. Use multiple like as mentioned below. I think the OP wants to search for the strings in multiple columns; your example searches in only one column.

Can we use multiple columns in where clause?

But the WHERE.. IN clause allows only 1 column.


1 Answers

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');
like image 95
ceyquem Avatar answered Sep 24 '22 22:09

ceyquem