How can I get a table of dates from the first day of the month, two months ago, to yesterday?

后端 未结 3 1230
情歌与酒
情歌与酒 2021-01-20 06:26

I have a situation that I would normally solve by creating a feeder table (for example, every date between five years ago and a hundred years into the future) for querying b

3条回答
  •  轮回少年
    2021-01-20 06:44

    just an idea (not even sure how you'd do this), but let's say you knew how many days you wanted. Like 45 days. If you could get a select to list 1-45 you could do date arithmetic to subtract that number from your reference data (ie today).

    This kind of works (in MySQL):

    set @i = 0; 
    SELECT @i:=@i+1 as myrow, ADDDATE(CURDATE(), -@i) 
    FROM some_table 
    LIMIT 10;
    

    The trick i have is how to get the 10 to be dynamic. If you can do that then you can use a query like this to get the right number to limit.

    SELECT DATEDIFF(DATE_SUB(CURDATE(), INTERVAL 1 DAY), 
                    DATE_SUB(LAST_DAY(CURDATE()), INTERVAL 2 MONTH))
    FROM dual;
    

提交回复
热议问题