I need to store few items and its properties in form of a key value pairs in the database (mySQL). I am planning to do it as following.
I'll use two tables items
and item_properties
.
items
itemId | itemName ------------------- 1923 | AC 1235 | Fridge 8273 | Heater
item_properties
itemId | property | value -------------------------------- 1923 | effect | cooling 1923 | consumption | efficient 1923 | type | split 1235 | effect | cooling 1235 | volume | 20 liters 8273 | effect | heating 8273 | consumption | efficient 8273 | heatMethod | coil
Now, if I have to select items whose 'effect' is 'cooling', I can do that using following query (which will give me 'AC' and 'Fridge' in result).
SELECT itemName FROM items i, item_properties p WHERE i.itemId=p.itemId AND (p.property = 'effect' AND p.value ='cooling');
I would like to know how write queries to select items that match multiple properties like
- select all items whose 'effect' is 'cooling' AND 'consumption' is 'efficient' (which would match item 'AC').
- select all items whose 'type' is 'split' OR 'heatMethod' is 'coil' OR 'consumption' is 'effecient' (which would match items 'AC' and 'Heater').
Kindly Help... Thanks in advance!!
Here is an example query:
I'll leave the
oR
query as something you can try yourself. It's simply adding more tables and usingOR
instead ofAND
in theWHERE
.Greetings!
I think your original query is maybe not right.. if your item_properties table has columns named (itemId, property, value) then your query should be:
Also, you're doing "implicit joins" here, and I don't know how much you want to learn about SQL vs. just wanting to get something to work, but there is another way to write your queries that I think is perhaps better if you're planning to stick with SQL databases for a while. It's no big deal, just that the second form is easier to read for me.
Your original query:
Would be rewritten using join syntax as:
I'll try to give both forms in answer to your questions...
select all items whose 'effect' is 'cooling' AND 'consumption' is 'efficient' (which would match item 'AC').
select all items whose 'type' is 'split' OR 'heatMethod' is 'coil' OR 'consumption' is 'effecient' (which would match items 'AC' and 'Heater').
Hope that helps!