I am creating a dynamic application. I have three tables: (EAV model style)
- Field Value (Item IDID), Field ID, Value)
- Field (Field ID, NameName)
-
Can you tell me how to write single query to start 20 records from all items of TRUE equal to FieldID = 4
Expected Result:
Stom = & Gt; Item IDID | Name | Field 1 | Field 2 | Field 3 each row = & gt; Item ID | ITEMNAME | Value1 Value 2 Important Things:
- The number of items per item is not known
- I need to write a query.
- The query will be running on 100 records, so performance is a matter of concern.
- I am using MySQL 5.0, so the solution needed for MYSQL
If the above question is not possible, do I reject tables? any advice?
EAV design is denormalized, this is a non-relational design There is no rule of generalization that will motivate you to use EAV design.
The SQL requires that when you write a query, you know the column, and also that each row of the result set is the same column with EAV, the only solution if you do not know every How many fields are there to bring them back as rows, not columns
SELECT i.ItemID, i.ItemName, f.FieldName, I add fields from V.Value items VALES v4 ON (v4.ItemID, v4.FieldID, v4.Value) = ( I.ItemID, 4, TRUE) JOIN Fields v contains i.itemID = v.ItemID v on field F f .ieldID = f.FieldID;
You have to process the rows in your application. For example, with PHP:
& lt ;? Php $ pdo = new PDO (...); $ Sql = "... above queries ..."; $ Archive = array (); Foreign currency ($ pdo-> query ($ sql) as the $ line) {$ id = $ row ["ItemID"]; If (! Array_key_exists ($ id, $ archive)) $ $ Collection [$ id] = new stdClass (); $ Collection [$ id] - & gt; Name = $ line ["item name"]; } $ Collection [$ id] - & gt; $ Row ["FieldName"] = $ line ["value"]; }
Now you have an array of objects, and each object corresponds to an item from the database. Each object has its respective fields.
Comments
Post a Comment