2012-07-17 51 views
0

我有兩個MySQL表,我想要做一個選擇查詢:我的目標是計算某個訂戶他過去七天從當前時間開始的點數。 第一張表格爲每位訂閱者呈現他從內容ID爲1或3時擊中特定內容的時間。 他可能在某一天沒有內容點擊,因此他今天不會有點數。複雜的加入和查詢選擇查詢

enter image description here

enter image description here

這些表在這些圖片中所示。 MY選擇查詢它是不完整的:

SELECT SUM(points) AS POINT, DAY FROM 
(SELECT content_hits.content_id, COUNT(*) * points AS points, 
DATE_FORMAT(hit_time, "%d-%m-%Y") AS DAY 
FROM content_hits JOIN content 
WHERE content_hits.content_id = content.content_id AND subscriber_id =1 
AND DATE_FORMAT(hit_time, "%Y-%m-%d") > (CURDATE() - INTERVAL 7 DAY) 
GROUP BY content_hits.content_id, DAY) AS tm 
GROUP BY DAY 
ORDER BY DAY DESC 

結果顯示在此圖中所示: enter image description here

我希望具有零計數爲天的結果:17-7-2102 16-7- 2012年15月7日至14日,2012年7月12日至2012年7月12日。 有什麼建議嗎?

回答

1

需要創建日曆表使用左連接

CREATE TABLE ints (i INTEGER); 
INSERT INTO ints VALUES (0), (1), (2), (3), (4), (5), (6), (7), (8), (9); 

LEFT JOIN日曆表查詢。

SELECT cal.date,COALESCE(a.point,0) as point 
FROM (
    SELECT DATE_FORMAT(CURDATE() + INTERVAL a.i * 10 - b.i DAY,"%Y-%m-%d") as date 
    FROM ints a JOIN ints b 
    ORDER BY a.i * 10 - b.i 
) cal LEFT JOIN 
(SELECT SUM(points) AS POINT, DAY FROM 
    (SELECT content_hits.content_id, COUNT(*) * points AS points, 
    DATE_FORMAT(hit_time, "%Y-%m-%d") AS DAY 
    FROM content_hits JOIN content 
    WHERE content_hits.content_id = content.content_id AND subscriber_id =1 
    AND DATE_FORMAT(hit_time, "%Y-%m-%d") > (CURDATE() - INTERVAL 7 DAY) 
    GROUP BY content_hits.content_id, DAY) AS tm 
    GROUP BY DAY 
)a 
ON cal.date = a.day 
WHERE cal.date BETWEEN CURDATE() - INTERVAL 7 DAY AND CURDATE() 
ORDER BY cal.date desc; 

SQL DEMO這裏。