acidpaul
acidpaul

Reputation: 165

Search functionality with pagination on a website

I'm developing a search functionality with pagination in my site to search for the product name and the brand name. I'm using this query to get the user's search request:

SELECT *
from products
WHERE name = 'optimum nutrition'
    OR brand = 'optimum nutrition' 
    OR name LIKE '%optimum%' 
    OR brand LIKE '%optimum%' 
    OR name LIKE '%nutrition%' 
    OR brand LIKE '%nutrition%'

I would like to display first the products that has the full 'optimum nutrition' in either the brand name and in the product name. How will I accomplish this?

Any suggestion would be greatly appreciated.

Upvotes: 1

Views: 473

Answers (4)

Alfred
Alfred

Reputation: 61771

First I believe name = 'optimum nutrition' will also be returned by name LIKE '%optimum%'. this can work if you design a correct query. But LIKE is very slow and should be avoided, especially database is large. I just found this interesting presentation which used October's Stackoverflow data and did full text searching on it. I think this comparison sheet is interesting:

enter image description here

Upvotes: 1

Shef
Shef

Reputation: 45589

Try:

SELECT *, 
CASE WHEN (name = 'optimum nutrition' OR brand = 'optimum nutrition') THEN 1 ELSE 0 END AS full_match,
CASE WHEN (name LIKE '%optimum%' OR brand LIKE '%optimum%' OR name LIKE '%nutrition%' OR brand LIKE '%nutrition%') THEN 1 ELSE 0 END AS half_match
FROM products 
WHERE (name = 'optimum nutrition' OR brand = 'optimum nutrition')
OR (name LIKE '%optimum%' OR brand LIKE '%optimum%' OR name LIKE '%nutrition%' OR brand LIKE '%nutrition%')
ORDER BY full_match, half_match

Upvotes: 2

James Allardice
James Allardice

Reputation: 165951

I would suggest looking into MySQL full text search. This involves adding a FULLTEXT index on columns you want to search, and then using a query that will look something like this:

SELECT * 
FROM products
WHERE MATCH(name, brand) AGAINST ('optimum') 

Upvotes: 0

Starx
Starx

Reputation: 78971

I will suggest you look into Zend Search Lucene, to put search functionality on your page.

Upvotes: 0

Related Questions