首页 > 解决方案 > 使用 mysql 中的间隔在数据库日期中添加月份

问题描述

我想通过加入计划表和事务表使用mysql间隔函数在事务日期中添加月份,但是这种方法不起作用但是如果我以静态方式将月份添加到事务日期它正在工作。

plan桌子:

plan_id    plan
1         6 month    
2         12 month    
3         3 month

transaction桌子:

id  user_id  subscribed_on   plan_id    
1     2       2020-04-04     1    
2     4       2019-02-22     2 

Mysql查询(不工作):

SELECT t.* FROM transaction t inner join plan p on p.plan_id=t.plan_id 
where t.user_id=2 and DATE_ADD(date(t.subscribed_on), INTERVAL p.plan) >= CURDATE() 
order by t.id desc

如果我以静态方式添加月份,则它工作正常:

SELECT t.* FROM transaction t inner join plan p on p.plan_id=t.plan_id 
where t.user_id=2 and DATE_ADD(date(t.subscribed_on),
INTERVAL 6 month) >= CURDATE() 
order by t.id desc

标签: mysqlsqldatetimeintervals

解决方案


不幸的是,数据中的字符串不等于间隔。一种方法是:

date(t.subscribed_on) + interval substring_index(plan, ' ') + 0 month

注意这里month是关键字,不是字符串。


推荐阅读