2012-07-17 70 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这里。