How to count number of time a particular item is added?
I am working on the web application developed in ASP.Net using C#. Allong with o开发者_开发百科ther feature, there is a feature which allow users to add various items to their personal list. The database tables relevant to above features are:
-------------------------
| Item |
-------------------------
| ItemId (Primary Key) |
| . . . & other attribs |
-------------------------
---------------------------
|List |
---------------------------
|ListId (Primary Key) |
|. . . and other attribs |
---------------------------
Since there is many to many relationship among above two table (i.e One Item is added in many lists and one list contains many items) So i create third table for that
---------------------------------
|ItemList |
---------------------------------
|ItemId (Foreign Key) |
|ListId (Foreign Key) |
|. . . and other Attributes |
---------------------------------
Now, I in need to maintain track that how many times a certain item is added in the list. In order to acheive this i have two possible options
- I add a new attribute in Item table and increment that value with one every time when a particular item is added to a certain list.
- The second option is that whenever i need to know that how many times a particular item is added in the list, then i will apply the SELECT Count Query (with where clause) on the ItemList table
Please suggest which approach is better and why? I am more declined towards the second approach, and regarding efficency i guess both have same
Option #1 will perform better for read operations because the count has already been aggregated. The downside to this approach is that you must:
- Manually update this number yourself for every insert and delete across your application.
- Update this number every time an item is added to the list. If you're application write to read ratio is high it might not be worth the effort
Option #2 will perform better if you're application has more insert/deletes compared to reads. The reason for this is that SQL Server only needs to calculate the count when it is needed.
I would suggest going with option #2 unless you have identified performance issues that would make you want to take a different approach.
Second approach is better from a data purity point of view. Let the data tell its own natural story - if you can work out how many lists an item is in by doing a quick Select count(ListId), ItemID as CountOfLists from ItemList Group By ItemID
then it's a far more attractive option than having to find all the spots in the code that modify ItemList
and make sure they update Item.Count
You'd consider the first option only if you were looking to denormalise/pre-aggregate the data for performance reasons. You've got to do extra work to make sure that the Count column in your Item table is always accurate (or, eventually accurate)
精彩评论