MySQL 8.0 参考说 MOD() + 1 returns 与 1 + MOD() 不同的结果
MySQL 8.0 Reference says MOD() + 1 returns different result from 1 + MOD()
我正在努力学习 MySQL 阅读官方 MySQL 8.0 reference/tutorial。
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> SELECT name, birth FROM pet
WHERE MONTH(birth) = 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> SELECT name, birth FROM pet
WHERE MONTH(birth) = 1 + MOD(MONTH(CURDATE()), 12);
我是不是遗漏了什么?
以下两个表达式是相同的,因为根据定义,加法是可交换的:
MOD(MONTH(CURDATE()), 12) + 1
1 + MOD(MONTH(CURDATE()), 12)
其中任何一个起作用的逻辑是,当当前日期的月份(介于 1 和 12 之间的数字)为 11 或更小时,12 的模数只是 returns 该数字,我们再加一个月。如果是十二月(12),表达式 12 % 12 returns 0,然后我们加一得到一月(1)。
我正在努力学习 MySQL 阅读官方 MySQL 8.0 reference/tutorial。 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> SELECT name, birth FROM pet
WHERE MONTH(birth) = 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> SELECT name, birth FROM pet
WHERE MONTH(birth) = 1 + MOD(MONTH(CURDATE()), 12);
我是不是遗漏了什么?
以下两个表达式是相同的,因为根据定义,加法是可交换的:
MOD(MONTH(CURDATE()), 12) + 1
1 + MOD(MONTH(CURDATE()), 12)
其中任何一个起作用的逻辑是,当当前日期的月份(介于 1 和 12 之间的数字)为 11 或更小时,12 的模数只是 returns 该数字,我们再加一个月。如果是十二月(12),表达式 12 % 12 returns 0,然后我们加一得到一月(1)。