我在保存“可协商日期”时遇到问题,因为这种方式每个月都有 30 天。我需要使用类似日期的类型(不是 varchar/text/blob/etc)来保存一个元素(2014-02-30)来保存它,因为在这个项目中我们需要它。可能吗?
最佳答案
可以使用 sql_mode ALLOW_INVALID_DATES 将此类 DATE“值”保存在 DATE
或 DATETIME
列中并且没有严格模式:
ALLOW_INVALID_DATES
Do not perform full checking of dates. Check only that the month is in the range from 1 to 12 and the day is in the range from 1 to 31. This is very convenient for Web applications where you obtain year, month, and day in three different fields and you want to store exactly what the user inserted (without date validation). This mode applies to DATE and DATETIME columns. It does not apply TIMESTAMP columns, which always require a valid date.
因此,检查允许的 session 日期可以使用触发器来完成,因为也没有其他检查。我认为对于此应用程序,每月 31 日将是无效日期。
示例:
CREATE TABLE example (
contable_date DATE NOT NULL
) ENGINE=INNODB;
-- set the sql_mode (here for the session)
SET @@SESSION.sql_mode = 'ALLOW_INVALID_DATES';
INSERT INTO example (contable_date) VALUES ("2014-02-30");
SELECT
DAY(contable_date) as cday,
MONTH(contable_date) as cmonth,
TIMESTAMPDIFF(DAY, contable_date, '2014-03-30') as cdiff
FROM
example;
结果:
cday cmonth cdiff
-------------------
30 2 28
使用我得到的 MySQL Workbench
SELECT contable_date FROM example
结果如下:
contable_date
-------------
2014-02-30
但这在 sqlfiddle.com 上不起作用。
不过我不推荐这样做,特别是因为人们无法使用严格的 SQL 模式。人们还应该考虑对日期和时间函数的影响。
关于mysql - 在 Mysql 上保存 2 月 30 日(日期格式),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25877242/