MySql每月x天之前选择记录

时间:2014-08-23 20:24:05

标签: mysql sql

我有一个表tbl_subscriptions和这样的列“id,user_name,join_date(date)”,我想根据join_date在每月7天之前选择用户,以便我可以发送通知继续他们的订阅下个月。我有这样的记录

1, user1, 2014-05-02
2, user2, 2014-05-04
3, user3, 2014-06-12
4, user4, 2014-06-20
4, user5, 2014-07-24

如果今天是2014-07-28,那么我想获得记录1和2.我尝试了下面的查询

SELECT  *, 
        datediff( date_format(date, '2014-07-%d'), now() ) as daysLeft 
FROM    tbl_subscriptions 
HAVING  daysLeft >= 0 
    AND daysLeft < 7

以上sql的问题是它只选择当前月份的记录,plz建议任何更好的查询。

2 个答案:

答案 0 :(得分:1)

这样做你想要的吗?

SELECT s.*, datediff(date, curdate()) as daysLeft
FROM tbl_subscriptions s
WHERE date >= curdate() and date < curdate() + interval 7 day;

编辑:

我明白了。这些是经常性订阅,您想要找到下一个订阅。以下逻辑应该有效:

select s.*,
       (case when day(date) >= day('2014-07-28')
             then day(date) - day('2014-07-28')
             else day(date) + day(last_day('2014-07-28')) - day('2014-07-28')
        end) as diff
from tbl_subscriptions s
having diff <= 7;

Here是SQL小提琴。

答案 1 :(得分:0)

好的,首先我不知道什么是订阅续订期。只检查日期(而不是整个期间)的想法对我来说没有意义。 但这将为您提供所需的输出。

SELECT *, 
       day(date) days, 
       day(last_day('2014-07-28')) as lastday, 
       day('2014-07-28') today, day(last_day('2014-07-28'))-day('2014-07-28') as diff
FROM tbl_subscriptions
having days <= (7-diff) or (days > today and days <= today+7)

这里是演示(架构归功于其中一个已删除的答案) - &gt; http://sqlfiddle.com/#!2/3cc4f

相关问题