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.