如果您的网站关闭一天会怎样?谁修复了您数据库中损坏的进度?如果 1 月 31 日星期日错过更新怎么办?你所有的价值观都将消失,并享受修复它的乐趣。
您应该只将视图计数存储在一个地方,并操纵该数据以满足您的需求。
您应该具有的表结构:
TABLE Articles
ID INT PK
...
TABLE Viewcount
Date DATE PK
Article_ID INT PK
NumViews INT
要更新观看次数:
INSERT INTO Viewcount (Date, Article_ID, NumViews)
VALUES(TODAY(), 12345, 1)
ON DUPLICATE KEY UPDATE NumViews=NumViews+1
并得到你的计数:
SELECT ar.ID,
today.numviews as 'today',
yesterday.numviews as 'yesterday',
thisweek.sum as 'week',
thismonth.sum as 'month',
thisyear.sum as 'year',
alltime.sum as 'alltime'
FROM Articles ar LEFT JOIN (
SELECT Article_id, NumViews
FROM Viewcount
WHERE Date = TODAY()
) 'today'
ON ar.ID = today.Article_ID
LEFT JOIN (
SELECT Article_id, NumViews
FROM Viewcount
WHERE Date = DATE_SUB(TODAY(), INTERVAL 1 DAY)
) 'yesterday'
ON ar.ID = yesterday.Article_ID
LEFT JOIN (
SELECT Article_id, SUM(NumViews) 'sum'
FROM Viewcount
WHERE YEAR(Date) = YEAR()
AND WEEK(Date) = WEEK()
GROUP BY Article_ID
) 'thisweek'
ON ar.ID = thisweek.Article_ID
LEFT JOIN (
SELECT Article_id, SUM(NumViews) 'sum'
FROM Viewcount
WHERE YEAR(Date) = YEAR()
AND MONTH(Date) = MONTH()
GROUP BY Article_ID
) 'thismonth'
ON ar.ID = thismonth.Article_ID
LEFT JOIN (
SELECT Article_id, SUM(NumViews) 'sum'
FROM Viewcount
WHERE YEAR(Date) = YEAR()
GROUP BY Article_ID
) 'thisyear'
ON ar.ID = thisyear.Article_ID
LEFT JOIN (
SELECT Article_id, SUM(NumViews) 'sum'
FROM Viewcount
GROUP BY Article_ID
) 'alltime'
ON ar.ID = alltime.Article_ID
或者只是以编程方式为您想要获取的时间段执行每个查询。