gpt4 book ai didi

mysql - 使用 join 和 group by 进行复杂的选择查询

转载 作者:行者123 更新时间:2023-11-29 14:22:39 25 4
gpt4 key购买 nike

我有两个 mysql 表,我想做一个选择查询:我的目标是计算某个订户从当前时间开始的过去 7 天的积分。第一个表显示每个订阅者点击内容 ID 1、2 或 3 中的某个内容的时间。他可能在某一天没有内容点击,因此他这一天不会获得积分。

enter image description here

enter image description here

表格如这些图片所示。 我的选择查询不完整:

   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-2012、14-7-2012 和 12-7-2012。有什么建议吗?

最佳答案

需要创建日历表以在左连接中使用

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

将日历表左连接到您的查询。

 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在这里。

关于mysql - 使用 join 和 group by 进行复杂的选择查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11517278/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com