我不喜欢其他答案,因此需要创建表。该查询在没有帮助程序表的情况下可以高效地完成它。
SELECT
IF(score IS NULL, 0, score) AS score,
b.Days AS date
FROM
(SELECT a.Days
FROM (
SELECT curdate() - INTERVAL (a.a + (10 * b.a) + (100 * c.a)) DAY AS Days
FROM (SELECT 0 AS a UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) AS a
CROSS JOIN (SELECT 0 AS a UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) AS b
CROSS JOIN (SELECT 0 AS a UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) AS c
) a
WHERE a.Days >= curdate() - INTERVAL 30 DAY) b
LEFT JOIN your_table
ON date = b.Days
ORDER BY b.Days;
因此,让我们对此进行剖析。
SELECT
IF(score IS NULL, 0, score) AS score,
b.Days AS date
if将检测没有得分的天并将其设置为0。b.Days是您选择从当前日期获取的已配置天数,最多1000。
(SELECT a.Days
FROM (
SELECT curdate() - INTERVAL (a.a + (10 * b.a) + (100 * c.a)) DAY AS Days
FROM (SELECT 0 AS a UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) AS a
CROSS JOIN (SELECT 0 AS a UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) AS b
CROSS JOIN (SELECT 0 AS a UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) AS c
) a
WHERE a.Days >= curdate() - INTERVAL 30 DAY) b
这个子查询是我在stackoverflow上看到的。它可以有效地生成从当前日期开始的过去1000天的列表。最后的WHERE子句中的间隔(当前为30)确定返回的天数。最大值为1000。可以轻松修改此查询以返回100多年的日期,但是1000对于大多数情况而言应该是好的。
LEFT JOIN your_table
ON date = b.Days
ORDER BY b.Days;
这是将包含分数的表带入其中的部分。您可以与日期生成器查询中选择的日期范围进行比较,以便在需要的地方填写0(分数将设置为NULL
初始值,因为它是LEFT JOIN
;;这在select语句中是固定的)。我也按日期排序,仅是因为。这是首选项,您也可以按分数排序。
在此之前,ORDER BY
您可以轻松地加入有关您在编辑中提到的用户信息的表,以添加最后一项要求。
我希望此版本的查询对某人有所帮助。谢谢阅读。