Need a MySQL query for selecting from a table storing key value pairs

泪湿孤枕 提交于 2019-11-28 12:35:57
Wolph

Here is an example query:

SELECT
  itemName
FROM
  items i,
JOIN
  item_properties effect
  ON i.itemId = effect.itemId AND effect.property = 'effect'
JOIN
  item_properties consumption
  ON i.itemId = consumption.itemId AND consumption.property = 'consumption'

WHERE effect.value = 'cooling' AND consumption.value = 'efficient';

I'll leave the oR query as something you can try yourself. It's simply adding more tables and using OR instead of AND in the WHERE.

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:

SELECT i.itemName FROM items i, item_properties p 
WHERE i.itemId=p.itemId AND p.property='cooling';

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:

SELECT itemName FROM items i, item_properties p 
WHERE i.itemId=p.itemId AND p.property='cooling';

Would be rewritten using join syntax as:

SELECT i.itemName FROM items i 
JOIN item_properties p ON i.itemId=p.itemId WHERE p.property='cooling';

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 itemName FROM items i, item_properties p 
WHERE i.itemId=p.itemId AND (p.property='cooling' AND p.value='consumption');

select i.itemName FROM items i JOIN item_properties p ON i.itemId=p.itemId 
WHERE p.property='cooling' AND p.value='consumption';

select all items whose 'type' is 'split' OR 'heatMethod' is 'coil' OR 'consumption' is 'effecient' (which would match items 'AC' and 'Heater').

select itemName FROM items i, item_properties p 
WHERE i.itemId=p.itemId AND ((p.property='type' AND p.value='split') OR 
(p.property='heatMethod' AND p.value='coil') OR 
(p.property='consumption' AND p.value='efficient'));

select itemName FROM items i JOIN item_properties p ON i.itemId=p.itemId 
WHERE (p.property='type' AND p.value='split') OR 
(p.property='heatMethod' AND p.value='coil') OR 
(p.property='consumption' AND p.value='efficient');

Hope that helps!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!