需要MySQL查询以从存储键值对的表中进行选择

Goj*_*e87 4 mysql key-value key-value-store

我需要在数据库(mySQL)中以键值对的形式存储少量项目及其属性.我打算按照以下方式做到这一点.

我将使用两个表itemsitem_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

现在,如果我必须选择"效果"为"冷却"的项目,我可以使用以下查询(这将在结果中给出'AC'和'Fridge').

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

我想知道如何编写查询来选择匹配多个属性的项目

  • 选择"效果"为"冷却"且"消费"为"高效"的所有项目(与项目"AC"匹配).
  • 选择"类型"为"拆分"的所有项目或"热量方式"为"线圈"或"消费"为"有效"(这将匹配项目"交流"和"加热器").

请帮助...提前致谢!!

Wol*_*lph 7

这是一个示例查询:

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';
Run Code Online (Sandbox Code Playgroud)

我会将oR查询保留为您可以自己尝试的内容.它只是添加更多的表并使用OR而不是ANDWHERE.