如果您有日期表,这些类型的查询最容易解决。在您的数据库中,一次性运行此批次以创建填充的日期表。
DROP PROCEDURE IF EXISTS FillDateTable;
delimiter //
CREATE PROCEDURE FillDateTable()
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ''
BEGIN
drop table if exists datetable;
create table datetable (thedate datetime primary key, isweekday smallint);
SET @x := date('2000-01-01');
REPEAT
insert into datetable (thedate, isweekday) SELECT @x, case when dayofweek(@x) in (1,7) then 0 else 1 end;
SET @x := date_add(@x, interval 1 day);
UNTIL @x >= '2030-12-31' END REPEAT;
END//
delimiter ;
CALL FillDateTable;
然后你可以使用常规的 LEFT JOIN
SELECT thedate
FROM datetable
LEFT JOIN posts on posts.date = datetable.thedate
WHERE posts.date IS NULL
当然,您不希望从 2000 年到 2030 年的所有“缺失”日期。将其限制为帖子表中的 MIN 和 MAX 日期(对于用户),即
SELECT thedate
FROM datetable
INNER JOIN (select min(date) postStart, max(date) postEnd
FROM posts
where userid=123) p on datetable.thedate BETWEEN p.postStart and p.postEnd
LEFT JOIN posts on posts.date = datetable.thedate
WHERE posts.date IS NULL