mysql eav,Mysql EAV将行匹配为字段或实体的属性值

My Mysql database has objects which are defined by an object type which is then joined to set it's properties. And it is based on the Entity Attribute Value model as pointed out by Spencer.

The database is a little more complicated then below but this should make my question a little more clear.

I have a mysql table objects which contains some basic information about an object say create_date, title,author and of course an id.

I also have a table object_properties which contains some more data about objects.

I have some trouble searching through them.

For example, an object might has both an end_date and start_date as a seperate property. These would each have their own row in object_properties.

How would one match the end and start date as they each have their own row?

Normally I would query it like this; select * from table where start_date > value AND end_date < value But I can't do this because each property is a separate row.

I tried the following query; `

select *

from object_properties

where object_id = 1

and ( (object_properties.type_id = 1)

and (object_properties.value = 2)

and ( (object_properties.type_id = 2)

and (object_properties.value = 2)

)

)

In the example above the type_id = 1 would be the start date and type_id =2 would be the end date but this did not seem to work.

I was thinking I am looking at it the wrong way.

I realize the title of my question might be wrong, I don't really know how storing data this way is called.

Here is the solution I used based on Matthews answer:

Here is what I ended up with: `

SELECT

o.title,

o.id,

op1.value AS start_date,

op2.value AS end_date

FROM object o

JOIN object_meta_values op1 ON op1.object_id=o.id AND op1.object_type_meta_id=28

JOIN object_meta_values op2 ON op2.object_id=o.id AND op2.object_type_meta_id=29

WHERE object_type_id = 11

AND (12 <= op1.value AND op1.value < 16 )

OR (12 < op2.value AND op2.value <= 16 )

OR (op1.value <= 12 AND 16 <= op2.value)

`. Thanks alot!

解决方案

You can use multiple left joins to do this.

SELECT

o.create_date,

o.title,

o.author,

op1.value AS start_date,

op2.value AS end_date,

...

FROM object o

LEFT JOIN object_properties op1 ON op1.object_id=o.object_id AND op1.type_id=1

LEFT JOIN object_properties op2 ON op2.object_id=o.object_id AND op2.type_id=2

Values that do not have properties will end up being null.

This method you don't have to have a second query to get the properties either.

EDIT

If you do not want to retrieve null values, then omit the left part of the left join.

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值