MySQL获取考虑了不同长度月份的月度发票记录

时间:2017-05-29 20:54:24

标签: php mysql date sql-date-functions

我有一个名为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.所以所有订阅都有created_at天'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));

1 个答案:

答案 0 :(得分:2)

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)。