我正在尝试比较同一表中的两个值,并检查是否存在差异。现在,我在cms_statistics_pages表中有1485条记录,但当下面的查询:
SELECT
cp.identifier,
COUNT(csp1.statID) AS hits,
COUNT(csp2.statID) AS hits_yesterday,
IF(COUNT(csp1.statID)>COUNT(csp2.statID),1,0) AS growth
FROM cms_pages cp
LEFT JOIN cms_statistics_pages csp1
ON csp1.pageID = cp.pageID
AND DATE(csp1.datetime) = '2012-07-20'
LEFT JOIN cms_statistics_pages csp2
ON csp2.pageID = cp.pageID
AND DATE(csp2.datetime) = '2012-07-19'
GROUP BY cp.identifier
被解雇,我得到以下结果:
identifier hits hits_yesterday growth
index 13395 13395 0
siden-er-under-opdatering 638 638 0
vores-historie 0 3 0
这不符合我的目的。然后如果我更改:
AND DATE(csp1.datetime) = '2012-07-20'
到将不匹配任何记录的日期
AND DATE(csp1.datetime) = '2012-07-21'
我现在的结果是这样的:
identifier hits hits_yesterday growth
index 0 141 0
siden-er-under-opdatering 0 29 0
vores-historie 0 3 0
现在命中率是正确的,所以我想知道当两个联接都包含一些数据时,查询是否会对记录进行多次计数。
来自cms_pages的示例数据:
pageID sectionID templateID标识符默认标题exclude_title1 1 1索引1欢迎来到SiteTech Framework 2012
来自cms_statistics_pages的示例数据:
statID前端后端页面ID部分ID面板日期时间1 0 1 34 6管理员2012-07-17 12:34:14
我看到了这篇文章,它提供了一种更高级的跨多个表计数的方法,这可能会阻止查询对同一记录进行多次计数。我自己还没试过——https://discussion.dreamhost.com/thread-9112.html
所以我对查询做了一些改动,找到了一个包括左联接和子查询的解决方案。我的查询现在看起来像:
SELECT
cp.identifier,
now.hits AS hits,
yd.hits AS hits_yesterday,
IF(now.hits>yd.hits,1,0) AS growth
FROM cms_pages AS cp
LEFT JOIN
(
SELECT
pageID,
COUNT(pageID) AS hits
FROM cms_statistics_pages
WHERE DATE(datetime) = '2012-07-20'
GROUP BY pageID
) now
ON now.pageID = cp.pageID
LEFT JOIN
(
SELECT pageID,
COUNT(pageID) AS hits
FROM cms_statistics_pages
WHERE DATE(datetime) = '2012-07-19'
GROUP BY pageID
) yd
ON yd.pageID = cp.pageID
这给了我这个正确的结果!:
identifier hits hits_yesterday growth
index 95 141 0
siden-er-under-opdatering 22 29 0
vores-historie NULL 3 0