我有一个名为subscriptions
的数据库表。表中的每一行都有一个created_at
日期,从即日起,每个月(之后)必须为订阅开具发票。
因此,在2017-05-29
上,所有日期为created_at
29'的订阅都必须开具发票,无论是月份还是年份。所以我想到:
SELECT * FROM subscriptions WHERE DAY(created_at) = DAY(DATE_SUB(CURDATE(), INTERVAL 1 MONTH))
但在这种情况下,当上个月有30天时,我会遇到麻烦,因为在30天,它返回30天,但在31天,它也返回30天。因此,日为“30”的所有订阅都将被开具两次发票。二月份也会有问题。
另一个问题是另一个问题,如果4月份没有31天,我如何开具2017-03-31的发票。
我可以在PHP中多次签入并检查当月是否已经开具了发票等等,但我想知道是否可以用MySQL来解决这个问题。
我根据上面的查询创建了一个sqlfiddle示例,其中包含一些将失败的日期。
# Create subscription table
CREATE TABLE `subscription` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`company` varchar(100) DEFAULT NULL,
`created_at` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
# Fill subscription table
INSERT INTO `subscription` (`id`, `company`, `created_at`)
VALUES
(1, 'Acme', '2017-04-15 09:56:00'),
(2, 'Equmbo', '2017-02-28 10:00:00'),
(3, 'Megajo', '2017-03-31 08:10:34'),
(4, 'Astrotude', '2017-04-30 08:10:49');
# This is my base query for monthly invoice
SELECT * FROM subscription WHERE DAY(created_at) = DAY(DATE_SUB(CURDATE(), INTERVAL 1 MONTH));
# On 28th March, also fine
SELECT * FROM subscription WHERE DAY(created_at) = DAY(DATE_SUB('2017-03-28', INTERVAL 1 MONTH));
# But on 29th March, Equmbo is invoice again
SELECT * FROM subscription WHERE DAY(created_at) = DAY(DATE_SUB('2017-03-29', INTERVAL 1 MONTH));
# On 30st April, Astrotude AND Megajo must be invoiced. Only Astrotude returns.
SELECT * FROM subscription WHERE DAY(created_at) = DAY(DATE_SUB('2017-04-30', INTERVAL 1 MONTH));
最佳答案
WHERE
/* don't invoice new subs from this month */
LAST_DAY(created_at)<LAST_DAY(CURDATE())
AND
(
/* exactly match sub's day value with today's day value */
DAY(created_at)=DAY(CURDATE())
OR
/* on last day of month, match sub's day if greater than today's day */
(CURDATE()=LAST_DAY(CURDATE()) AND DAY(created_at)>DAY(CURDATE()))
)
CURDATE()和LAST_DAY()返回完整日期字符串(yyyy-mm-dd)。
DAY()返回一个整数(d或dd)。
关于php - MySQL获取考虑不同月份长度的月度发票记录,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44250165/