I have worked with various applications and have repeatedly come across this situation. So far I have not figured out what works best.
Here's the script:
- I have an application on my desktop or on the Internet.
- I need to get simple documents from a database. The document contains general information and details about the parts, so the database:
GeneralDetails table:
| DocumentID | DateCreated | Owner | | 1 | 07/07/07 | Naruto | | 2 | 08/08/08 | Goku | | 3 | 09/09/09 | Taguro |
ItemDetails table
| DocumentID | Item | Quantity | | 1 | Marbles | 20 | | 1 | Cards | 56 | | 2 | Yo-yo | 1 | | 2 | Chess board | 3 | | 2 | GI Joe | 12 | | 3 | Rubber Duck | 1 |
As you can see, tables have a one-to-many relationship. Now, to get all the documents and their corresponding elements, I always do one of two things:
Method 1 - multi-channel (pseudo-code):
Documents = GetFromDB("select DocumentID, Owner " + "from GeneralDetails") For Each Document in Documents { Display(Document["CreatedBy"]) DocumentItems = GetFromDB("select Item, Quantity " + "from ItemDetails " + "where DocumentID = " + Document["DocumentID"] + "") For Each DocumentItem in DocumentItems { Display(DocumentItem["Item"] + " " + DocumentItem["Quantity"]) } }
Method 2 - A lot of unnecessary data (pseudocode):
DocumentsAndItems = GetFromDB("select g.DocumentID, g.Owner, i.Item, i.Quantity " + "from GeneralDetails as g " + "inner join ItemDetails as i " + "on g.DocumentID = i.DocumentID") //Display...
I used the first method when I was in college for desktop applications, the performance was not bad, so I realized that everything was in order.
Until one day I saw the article βMake the Internet faster,β she says that many round trips to the database are bad; therefore, since then I have used the second method.
In the second method, I avoided round trips, using an inner join to retrieve the first and second tables at once, but it creates unnecessary or redundant data. See Result Set.
| DocumentID | Owner | Item | Quantity | | 1 | Naruto | Marbles | 20 | | 1 | Naruto | Cards | 56 | | 2 | Goku | Yo-yo | 1 | | 2 | Goku | Chess board | 3 | | 2 | Goku | GI Joe | 12 | | 3 | Taguro | Rubber Duck | 1 |
The result set has redundant DocumentID and Owner . It looks like an abnormal database.
Now the question arises: how can I avoid round trips and at the same time avoid redundant data?