我想使用mysql interval函数通过连接计划表和事务表在事务日期中添加月份,但是这种方法不起作用,但如果我以静态方式将月份添加到事务日期中,它是有效的。
plan表:
plan_id plan
1 6 month
2 12 month
3 3 monthtransaction表:
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发布于 2020-10-10 21:24:16
MySQL不支持以这种方式使用interval。与其他数据库不同(例如Postgres ),单位参数是一个关键字,而不是文字字符串。
我怀疑您的表可能存储了除月份之外的其他时间间隔(例如,年、日等)。如果是这样,您可以使用字符串函数和case表达式来适应不同的可能值,例如:
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表达式处理单位并相应地生成适当的文字间隔。
发布于 2020-10-10 21:17:53
不幸的是,数据中的字符串并不等同于间隔。一种方法是:
date(t.subscribed_on) + interval substring_index(plan, ' ') + 0 month注意,month是一个关键字,而不是字符串。
发布于 2020-10-10 22:04:59
尝试强制plan表中的plan列为整数。似乎不可能将字符串转换为间隔。
我试着这样做:
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(不返回结果,因为您的示例数据中没有足够高的日期...)
https://stackoverflow.com/questions/64293842
复制相似问题