I am building a dynamic application. I have three tables : ( EAV model style)
- Items ( ItemId, ItemName)
- Fields (FieldId, FieldName)
- Field Values ( ItemID, FieldId, Value)
Can you tell me how to write SINGLE query to get starting 20 records from ALL items where FieldId=4 is equal to TRUE.
Expected Result :
Columns => ItemID | Name | Field1 | Field2 | Field3
Each Row=> ItemId | ItemName| Value1 | Value2 | Value3
Important concerns :
- Number of fields per item are not known
- I need one to write ONE query.
- Query will be running on 100K records, so performance is concern.
- I am using MySQL 5.0, so need solution for MYSQL
Should I denormalize the tables if above query is not possible at all ? Any advice ?
The EAV design is denormalized. That is, it's a non-relational design. There is no rule of normalization that would lead you to use the EAV design.
SQL requires that you know the columns when you write the query, and also that every row of the result set has the same columns. With EAV, the only solution if you don't know how many fields per item is to fetch them back as rows, not columns.
You have to process the rows in your application. For instance, with PHP:
Now you have an array of objects, and each object corresponds to an item from the database. Each object has its own respective set of fields.