2012-07-23 72 views
2

我試圖比較同一個表中的兩個值,並檢查是否有差異。 現在,我有1485條記錄中cms_statistics_pages表,但在下面的查詢:MySQL比較同一個表上的兩個值

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 

現在的點擊率是正確的,所以我m想知道當兩個連接都包含一些數據時,查詢是否多次計算記錄。從cms_pages

示例數據:從cms_statistics_pages

 

    pageID sectionID templateID identifier default title exclude_title 
    1  1  1   index 1  Welcome to SiteTech Framework 2012 

示例數據:

 

    statID frontend backend  pageID sectionID panel datetime 
    1  0  1  34  6  admin 2012-07-17 12:34:14 

回答

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