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

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:

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值