sarah
answered Apr 26 '23 00:00
Sure, here's an example query that uses MATCH() AGAINST() in MySQL:
Suppose we have a table called products with columns product_id, name, description, and category, and we want to search for products that match the search term "computer" in either the name or description columns. We can use the following query:
SELECT product_id, name, description, category, MATCH(name, description) AGAINST('computer') as relevance
FROM products
WHERE MATCH(name, description) AGAINST('computer')
ORDER BY relevance DESC
In this example, we are selecting the product_id, name, description, and category columns from the products table. We are also using the MATCH() function to search for the term "computer" in the name and description columns. The AGAINST() function takes the search term as an argument.
The MATCH() function returns a relevance score for each matching record, which indicates how well the record matches the search term. We are using the AS keyword to name this calculated column relevance.
We are then using the WHERE clause to filter the results to only include records that match the search term. Finally, we are using the ORDER BY clause to sort the results in descending order by the relevance score.
Note that in order to use MATCH() AGAINST() with full-text searching, you need to have a full-text index on the columns you want to search. You can create a full-text index using the FULLTEXT keyword in the CREATE TABLE or ALTER TABLE statement.