I have a database table called subscriptions
. Each row in the table has a created_at
date, from this day on, every month (afterwards) the subscription must be invoiced.
So on 2017-05-29
, all subscriptions with a created_at
day == '29' must be invoiced, regardless the month or year. So I thought of this:
SELECT * FROM subscriptions WHERE DAY(created_at) = DAY(DATE_SUB(CURDATE(), INTERVAL 1 MONTH))
But in that case I get in trouble when the previous month has 30 days, because on the 30th, it returns 30, but on the 31st it also returns 30. So all subscriptions with a created_at
day '30' will be invoiced twice. Also February will give issues.
Another issue is the other way around, how will I invoice 2017-03-31 if there is no 31st day in April.
I could do multiple check in PHP and check if already invoiced that month etc. But I wonder if I could just fix this with MySQL.
I created a sqlfiddle example, based on the query above with some dates that will fail.
# 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() and LAST_DAY() return a full date string (yyyy-mm-dd).
DAY() returns an integer (d or dd).