Amara
Amara

Reputation: 211

Multiple Queries on Same field in tables

Really hope someone can help me or at least point me in the right direction. I working on a product site, that allows visitors to filter their results using a menu on side of the product results, similar to what www.asos.com have done. Basically, they can chose product type, style,price,fit ... etc. Each of these fiter types, have their own table and a reference table which links each value to the products table. EG There is a

Products table with productkey and all other product information Colours table, with the following fields, Colour_ID, Name Colourref table with productkey, Colour_ID

I'm using MySQL and PHP. I know how to query the database and display the data if the visitor makes one selection from each filter type and then to display the counts for each attribute, but I'd really like to be able to allow them to make multiple selections and then calculate the counts for each attribute, based on what's been selected. I've looked into how this should be done, and I've seen that subqueries are an option, but I'm concerned about how many subqueries I would need to create as I have 9 filter groups, that can have a large number of values. There are currently, 1/2 million products in the database, and this grow over time. I'm capturing the values that need to be queried via the url, so as an example

page=1&view=20&product=125,137,147&type=1,3,5&colour=3,9,5&material=187,345

As you can see from the example, I can have multiple values for each time. I tried writing a query using AND. Example, product = 125 AND product = 137, but that doesn't work.

Does anyone have any advice on the best way to go about doing this even if it's just a point in the right direction?

Any help will be greatly appreciated

Thank you in Advance

Vivien

Upvotes: 2

Views: 264

Answers (1)

Chris
Chris

Reputation: 3121

Basically you answered your own question already:

SELECT ...
FROM ...
WHERE   (product = 125 OR product = 137) AND  
        (colour = 3 OR colour = 8 OR colour = 5) ...

You need to use OR instead of AND if you want to select several products, colours and so on. If you want both a product and colour then you need to combine those using AND in between. There is no need for subqueries here.


It's easier to use IN though:

SELECT ...
FROM ...
WHERE product IN (125, 137, 147) AND colour IN (3, 5, 8)

A more complete example of this SQL code:

SELECT p.* 
FROM Products p

LEFT JOIN Colourref cr
ON cr.productkey = p.productkey

LEFT JOIN Colours c
ON c.Colour_ID = cr.Colour_ID

WHERE 
    p.productkey IN (1, 2, 4)
    AND c.Colour_ID IN (1, 2)

This will select all products that have the ID 1, 2 or 4 which have the colours 1 or 2.

It left joins the required tables on the IDs and then filters the desired values.

Upvotes: 2

Related Questions