Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to search multiple columns in MySQL?

I'm trying to make a search feature that will search multiple columns to find a keyword based match. This query:

SELECT title FROM pages LIKE %$query%; 

works only for searching one column, I noticed separating column names with commas results in an error. So is it possible to search multiple columns in mysql?

like image 294
George Avatar asked Mar 25 '10 10:03

George


People also ask

How do I search for 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 find columns in MySQL?

mysql> SELECT count(*) AS NUMBEROFCOLUMNS FROM information_schema. columns -> WHERE table_name ='NumberOfColumns'; Here is the output. The alternate query to find the number of columns.

How do I sort multiple columns in MySQL?

How do I sort multiple columns in MySQL? Summary. Use the ORDER BY clause to sort the result set by one or more columns. Use the ASC option to sort the result set in ascending order and the DESC option to sort the result set in descending order.


2 Answers

If it is just for searching then you may be able to use CONCATENATE_WS. This would allow wild card searching. There may be performance issues depending on the size of the table.

SELECT *  FROM pages  WHERE CONCAT_WS('', column1, column2, column3) LIKE '%keyword%' 
like image 175
Terra Walker Avatar answered Oct 04 '22 00:10

Terra Walker


You can use the AND or OR operators, depending on what you want the search to return.

SELECT title FROM pages WHERE my_col LIKE %$param1% AND another_col LIKE %$param2%; 

Both clauses have to match for a record to be returned. Alternatively:

SELECT title FROM pages WHERE my_col LIKE %$param1% OR another_col LIKE %$param2%; 

If either clause matches then the record will be returned.

For more about what you can do with MySQL SELECT queries, try the documentation.

like image 24
akamike Avatar answered Oct 04 '22 02:10

akamike