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?
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.
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.
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.
But the WHERE.. IN clause allows only 1 column.
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With