首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在mysql中使用interval在数据库日期中添加月份

问在mysql中使用interval在数据库日期中添加月份
EN

Stack Overflow用户
提问于 2020-10-10 21:16:25
回答 3查看 69关注 0票数 0

我想使用mysql interval函数通过连接计划表和事务表在事务日期中添加月份,但是这种方法不起作用,但如果我以静态方式将月份添加到事务日期中,它是有效的。

plan表:

代码语言:javascript
复制
plan_id    plan
1         6 month    
2         12 month    
3         3 month

transaction表:

代码语言:javascript
复制
id  user_id  subscribed_on   plan_id    
1     2       2020-04-04     1    
2     4       2019-02-22     2 

Mysql查询(不工作):

代码语言:javascript
复制
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

如果我以静态的方式添加月份,那么它工作得很好:

代码语言:javascript
复制
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
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2020-10-10 21:24:16

MySQL不支持以这种方式使用interval。与其他数据库不同(例如Postgres ),单位参数是一个关键字,而不是文字字符串。

我怀疑您的表可能存储了除月份之外的其他时间间隔(例如,年、日等)。如果是这样,您可以使用字符串函数和case表达式来适应不同的可能值,例如:

代码语言:javascript
复制
select t.* 
from transaction t 
inner join plan p on p.plan_id = t.plan_id 
where 
    t.user_id = 2 
    and date(t.subscribed_on) + case substring_index(p.plan, ' ', -1)
        when 'year'  then interval substring_index(p.plan, ' ', 1) year
        when 'month' then interval substring_index(p.plan, ' ', 1) month
        when 'day'   then interval substring_index(p.plan, ' ', 1) day
    end
    >= current_date
order by t.id desc

这里的逻辑是将存储的间隔字符串分为两部分:数字和单位;case表达式处理单位并相应地生成适当的文字间隔。

票数 1
EN

Stack Overflow用户

发布于 2020-10-10 21:17:53

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

代码语言:javascript
复制
date(t.subscribed_on) + interval substring_index(plan, ' ') + 0 month

注意,month是一个关键字,而不是字符串。

票数 1
EN

Stack Overflow用户

发布于 2020-10-10 22:04:59

尝试强制plan表中的plan列为整数。似乎不可能将字符串转换为间隔。

我试着这样做:

代码语言:javascript
复制
WITH
plan( plan_id,plan) AS (
          SELECT 1,'6 month'
UNION ALL SELECT 2,'12 month'    
UNION ALL SELECT 3,'3 month'
)
,
transaction(id,user_id,subscribed_on,plan_id) AS (
          SELECT 1,2,DATE '2020-09-04',1    
UNION ALL SELECT 2,4,DATE '2019-02-22',2 
)
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 CAST(REPLACE(plan,' month','') AS SIGNED) MONTH
    ) >= CURDATE()
ORDER BY t.id DESC

(不返回结果,因为您的示例数据中没有足够高的日期...)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64293842

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档