gpt4 book ai didi

mysql - date_add 并永远重复

转载 作者:行者123 更新时间:2023-11-29 08:32:50 24 4
gpt4 key购买 nike

我有一个用户警报表,其中我们必须按照用户定义的时间间隔向用户发送警报,例如 0(仅一次)、3 个月、6 个月、1 年

所以我设计了一个这样的表格

id   |   user_id    |   alert_date            |  repeat_int
-----+--------------+-------------------------+-------------
12 | 747 | 2013-04-19 00:00:00 | 0
13 | 746 | 2013-03-19 00:00:00 | 1
14 | 745 | 2012-04-19 00:00:00 | 0
15 | 744 | 2013-04-19 00:00:00 | 0
16 | 743 | 2013-05-19 00:00:00 | 0

我们将在“alert_date”前一天发送提醒

通过以下查询我可以获取数据

SELECT al.id,
al.user_id,
al.alert_date,
al.repeat_int AS repunit
FROM alerts AS al
WHERE DATE_ADD(alert_date,INTERVAL repeat_int MONTH)=date_add(CURRENT_DATE,INTERVAL 1 DAY)
OR date(al.alert_date)=date_add(CURRENT_DATE,INTERVAL 1 DAY)

它的工作文件,但我真正的问题是

重复只会有效一次,我们需要它在每个间隔重复

即。如果警报日期为 2012-03-14 并且 Repeat_int 为 0 - 只需工作一次但如果警报日期是 2012-03-14 并且 Repeat_int 是 1 - 需要从 2012-03-14 起每 14 日工作一次

如果警报日期是 2012-03-14 并且 Repeat_int 是 3 - 需要每三个月的 14 工作一次。即 2012-03-14、2012-06-14、2012-09-14 等警报。 ..

有什么办法可以做到这一点吗?

最佳答案

更新

OP 已更改其架构以响应评论,因此查询本质上是:

SELECT *
FROM alerts
WHERE CURRENT_DATE + INTERVAL 1 DAY = COALESCE(next_alert_date, alert_date);

这会在第一次运行时处理“next_alert_date”为 NULL 的情况。

原始答案

对于原始架构:

SELECT *
FROM alerts
JOIN (SELECT CURRENT_DATE + INTERVAL 1 DAY AS tomorrow) d
WHERE -- We want to alert if
-- 1. Tomorrow is the alert_date
tomorrow = alert_date
OR
--
-- 2. Tomorrow is "repeat_int" months removed from alert_date, falling on
-- the same day of the month or on the end of the month if the original
-- alert_date day of month is later in the month than is possible for us
-- now. E.g., 2013-01-31 repeated monthly is adjusted to 2013-02-28.
(
PERIOD_DIFF(DATE_FORMAT(tomorrow, '%Y%m'), DATE_FORMAT(alert_date, '%Y%m'))
MOD repeat_int = 0
AND
-- Make sure we are at the same day of the month
( (DAYOFMONTH(tomorrow) = DAYOFMONTH(alert_date)
OR
-- Or, if the day of the alert is beyond the last day of our month,
-- that we are at the end of our month.
(LAST_DAY(alert_date) > LAST_DAY(tomorrow)
AND
DAYOFMONTH(tomorrow) = LAST_DAY(tomorrow)) )
);

关于mysql - date_add 并永远重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16075010/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com