Forum Moderators: open

Message Too Old, No Replies

Problem with creating dynamic query

         

gublooo

4:57 pm on Dec 19, 2007 (gmt 0)

10+ Year Member



I'm having trouble writing a SQL query and would appreciate any help. Basically I have a database structure with a table for Products and a table for storing product attributes.
Showing minimum fields, the tables look like:

Product:
product_id¦name
1 ¦My TV
2 ¦HD TV
3 ¦Plasma TV

Product_Choices:
choice_id¦product_id¦choice_value
1 ¦1 ¦ Sony
2 ¦1 ¦ Black
3 ¦1 ¦ 32
4 ¦2 ¦ Sony
5 ¦2 ¦ Silver
6 ¦2 ¦ 32
7 ¦3 ¦ Sony
8 ¦3 ¦ Silver
9 ¦3 ¦ 42

Now if a user wants to search all Sony products, my query looks like


SELECT product_id
FROM PRODUCT_CHOICES
WHERE value='Sony'

This will return 1,2,3

But what if a user wants to search for all products with value Sony and 32
This query wont work:


SELECT product_id
FROM PRODUCT_CHOICES
WHERE value='Sony' and value='32'

But this will work

SELECT product_id
FROM PRODUCT_CHOICES pc1,
PRODUCT_CHOICES pc2
WHERE pc1.value='Sony'
AND pc2.value='32'
and pc1.PRODUCT_ID=pc2.PRODUCT_ID

This will return 1,2
But the problem is, this query has to be built dynamically depending upon the options the user chooses.
Say if a user chooses 3 options, then I'll have to make an inner join 3 times - which is not a good idea.

Is there a better way to do this. I'm beginning to doubt my database structure. How else can I store and retrieve a product and its attributes. The design looks good if you want to get all the attributes of a product based on the product ID, but if you want to go in the reverse direction, ie to get all products that have certain attributes, it seems to get difficult.

Appreciate your help.
Thanks