Le开发者_JAVA百科t's say we have a table for items that looks like this
item_id
item_visits
What should we add to this table, to be able to sort these items based on how many visits they have had in the last 7 days.
And how do we query that to the db?
Sorry, I misunderstood the ask... Well, of course you need to add a column named VisitTime which has type datetime.
After that I would suggest to create a set of views to help you making the query. For example a view named DailyVisit which has the amount of view in day(indicated by a date) for every item.
Your table is a bit confused.
You don't want to keep track of the number of item visits.
You just want to keep track of when an item was visited and maybe by whom and and where and which item.
I would suggest the following:
table visit
------------
id integer not null primary key auto_increment
item_id integer not null foreign key fk_item_id
references item(id) on delete cascade on update cascade
visitor_id integer not null foreign key fk_visitor_id
references visitor(id) on delete cascade on update cascade
visit_date timestamp not null default current_timestamp
engine = InnoDB
This should give you all the details you need to know the visits per item and get details about items and visitors as well.
-- select total number of visits per item for the last week.
SELECT
COUNT(*) as NrOfVisits
, i.name as ItemName
FROM visit v
INNER JOIN item i ON (v.item_id = i.id)
WHERE v.visit_date BETWEEN now() AND DATE_SUB(now(), INTERVAL 7 DAY)
GROUP BY v.item_id WITH ROLLUP
精彩评论