我正在尝试阅读官方 MySQL 8.0 引用/教程来学习 MySQL。 https://dev.mysql.com/doc/refman/8.0/en/date-calculations.html
在解释如何使用计算获得一月的段落中,它说
A different way to accomplish the same task is to add 1 to get the next month after the current one after using the modulo function (MOD) to wrap the month value to 0 if it is currently 12:
mysql> 选择名字,出生来自宠物
WHERE MONTH(出生) = MOD(MONTH(CURDATE()), 12) + 1;
MONTH() returns a number between 1 and 12. And MOD(something,12) returns a number between 0 and 11. So the addition has to be after the MOD(), otherwise we would go from November (11) to January (1).
我的问题是为什么加法应该在MOD()之后? 即使添加在 'MOD(MONTH(CURDATE()), 12)' 之前,我也会得到相同的结果,如下所示。
mysql> 选择名字,出生来自宠物
WHERE MONTH(出生) = 1 + MOD(MONTH(CURDATE()), 12);
我在这里遗漏了什么吗?
最佳答案
以下两个表达式是相同的,因为根据定义,加法是可交换的:
MOD(MONTH(CURDATE()), 12) + 1
1 + MOD(MONTH(CURDATE()), 12)
其中任何一个起作用的逻辑是,当当前日期的月份(1 到 12 之间的数字)为 11 或更少时,模数除以 12 只是返回该数字,然后我们将一个月添加到它。对于 12 月 (12),表达式 12 % 12 返回 0,然后加一以获得 1 月 (1)。
关于MySQL 8.0 Reference 说 MOD() + 1 返回与 1 + MOD() 不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58576652/