为什么在MySQL中使用两位数年份的日期值不是一个好习惯?

2023年12月16日11:57:26

YEAR(2)以2位数格式存储一年。例如,我们可以写69来存储1969。在年份(2)中,可以将年份指定为1970到2069(70到69)。

MySQL借助以下规则来解释两位数的年份值-

  • 00-69范围内的年份值将转换为2000-2069。

  •  70-99范围内的年份值转换为1970-1999。

我们不能将日期值存储为两位数格式,因为随着世纪的来临,以这种格式存储的值变得模糊。

通过以下MySQL示例可以更清楚地理解-

mysql> Create Table year_test(val year(2));

mysql> insert into year_test(val) values('70');

mysql> insert into year_test(val) values('00');

mysql> select * from year_test;
+-----+
| val |
+-----+
| 70  |
| 00  |
+-----+
2 rows in set (0.00 sec)

mysql> select * from year_test where val = '1970';
+-----+
| val |
+-----+
| 70  |
+-----+
1 row in set (0.03 sec)

mysql> select * from year_test where val = '2000';
+-----+
| val |
+-----+
| 00  |
+-----+
1 row in set (0.00 sec)

mysql> select * from year_test where val = '1900';
Empty set (0.06 sec)

通过将00存储为“ val”,我们不确定是哪一年表示“ 1900”或“ 2000”。MySQL将其解释为2000年。


  • 更新时间:2023年12月16日11:57:26 ,共 779 字。