I’m trying to compare two values in the same table, and check if there is a difference.
Right now, I have 1485 records in the cms_statistics_pages table, but when the query below:
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
..is fired, I get these results:
identifier hits hits_yesterday growth
index 13395 13395 0
siden-er-under-opdatering 638 638 0
vores-historie 0 3 0
Which is not correct for my purpose. Then if I change:
AND DATE(csp1.datetime) = '2012-07-20'
to a date that will match no records
AND DATE(csp1.datetime) = '2012-07-21'
My result now looks like this:
identifier hits hits_yesterday growth
index 0 141 0
siden-er-under-opdatering 0 29 0
vores-historie 0 3 0
Now the hits are correct, so I’m wondering if the query counts the records multiple times when both the joins contains some data.
Example data from cms_pages:
pageID sectionID templateID identifier default title exclude_title
1 1 1 index 1 Welcome to SiteTech Framework 2012
Example data from cms_statistics_pages:
statID frontend backend pageID sectionID panel datetime
1 0 1 34 6 admin 2012-07-17 12:34:14
So I’ve been messing around a bit with the query, and found a solution which includes left joins and sub queries. My query now looks like:
Which gave me this correct result!: