I make a site with articles and I want to count the views of each article for displaying most popular articles: today, this week and this month.
How would you do the database schema for that?
If it is enough to know the number of times an article was displayed you could use something like this:
daily_article_views(
,article_id
,view_date
,view_count
,primary key(article_id, view_date)
,foreign key(article_id) references articles
);
For each article view, you would lookup a row in the table using the Current Date and the ID of the article currently being viewed. If a row exists, you increment the counter. If no row exists, you insert it with a value of 1 for view_count (and a truncated date). You can then rollup the data from this table using SUM(view_count) to weekly, monthly or yearly figures as neccesary.
However, if you need to store information about each individual view, you could use a table structure similar to the following.
article_views(
,view_id
,article_id
,view_date
,additional_data_about_each_view
,primary key(view_id)
,foreign key(article_id) references articles
);
The additional_data_about_each_view would be columns representing some user id, maybe IP address or whatever you need to store. Note that in this design you will store the time of article view including the time (hour, minutes, seconds). This would eable you to analyze the data over the course of a day, exactly when the articles are viewed.
The downside with the last design is that it will potentially generate a lot of data which may make queries slower. Of course, nothing stops you from implementing both alternatives :)
If you will definitely never be interested in time of day information then you could use a table with 3 columns
article_id
date
view_count
You might not necessarily want to increment the view_count
column for every hit though. You could cache some information in your application and update in batches.
来源:https://stackoverflow.com/questions/4366830/count-visitor-hits-per-day-last-week-and-last-month