SQL query that returns all dates not used in a table

后端 未结 4 1018
一个人的身影
一个人的身影 2020-12-18 10:44

So lets say I have some records that look like:

2011-01-01 Cat
2011-01-02 Dog
2011-01-04 Horse
2011-01-06 Lion

How can I construct a query

4条回答
  •  独厮守ぢ
    2020-12-18 11:14

    One solution would be to create a separate table with one column to hold all dates from now until eternity (or whenever you expect to stop blogging). For example:

    CREATE TABLE Dates (dt DATE);
    INSERT INTO Dates VALUES ('2011-01-01');
    INSERT INTO Dates VALUES ('2011-01-02');
    ...etc...
    INSERT INTO Dates VALUES ('2099-12-31');
    

    Once this reference table is set up, you can simply outer join to determine the unused dates like so:

    SELECT d.dt 
    FROM Dates d LEFT JOIN Blogs b ON d.dt = b.dt 
    WHERE b.dt IS NULL
    

    If you want to limit the search to two weeks in the future, you could add this to the WHERE clause:

    AND d.dt BETWEEN NOW() AND ADDDATE(NOW(), INTERVAL 14 DAY)
    

提交回复
热议问题