Question

I've to extract all products from "product" table (DBMS: MySQL, Adapter: PDO), ordering result by the number of filtering criteria that are matched.

This is an example of raw SQL query (but I'll use Zend_DB classes and adapters):

    SELECT *
    FROM product 
    WHERE price < 300
    AND price > 100
    AND discount = TRUE
    AND used = FALSE
    AND type = MEAL

and a lot of other optionals filter criteria that end user could introduce from the UI.

All the filter criteria (where conditions in the query) could be optionally matched by the user in the form of the web app, and the GOAL the my algorithm is to order the results from the most matching criteria product to the product that match at least 2 criteria.

I'm using Zend Framework 1, and my question is: Is there any Zend class that could help me in this particular algorithm? If no, could anyone suggest a solution for this problem?

I've tried a crude solution where I'll compose the query considering all the possible combination of the criteria, but considering that there are a lot of criteria, the algorithm complexity increases so much, so I suppose that an alternative may exists. Thanks

Was it helpful?

Solution

Something like...

SELECT * FROM (
   SELECT P.*,
case when price < 300 and price >  100 then 1 else 0 end + 
case when discount = true then 1 else 0 end + 
case when used = false then 1 else 0 end + 
case when type = 'MEAL' then 1 else 0 end +
... (for each possible outcome) as Matches
    FROM product p)
Where matches > 2
Order by Matches descending
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top