我正在尝试比较同一个表中的两个值,并检查是否存在差异。 现在,我在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 identifier default title exclude_title 1 1 1 index 1 Welcome to SiteTech Framework 2012
来自cms_statistics_pages的示例数据:
statID frontend backend pageID sectionID panel datetime 1 0 1 34 6 admin 2012-07-17 12:34:14
答案 0 :(得分:0)
我发现这篇文章提供了一种更高级的方法来计算多个表,这可能会阻止查询多次计算同一记录。 Haven没有亲自尝试过 - https://discussion.dreamhost.com/thread-9112.html
答案 1 :(得分:0)
所以我一直在搞乱查询,并找到了一个包含左连接和子查询的解决方案。我的查询现在看起来像:
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