如何在 MySQL/MariaDB 中添加一个生成的列,该列将根据其他列中的信息计算日期?

How can I add a generated column in MySQL/MariaDB that will caculate a date from information in other columns?

我了解如何使用 MariaDB 添加生成的列(支持与 MySQL 相同的语法),并且已使用简单的算术运算完成此操作 table。但是,当我尝试使用 DATE_SUB 函数时,出现语法错误:

SQL Error [1064] [42000]: (conn=28594) You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'WEEKS)) STORED' at line 3

我使用的代码是:

ALTER TABLE `ExampleTable`
ADD COLUMN `DOB` DATE
AS (DATE_SUB (`DateExpected`, INTERVAL `Age` WEEKS)) STORED; 

我想根据 DateExpected 和 Age 值计算 DOB。

来自创建 TABLE:

  `DateExpected` date DEFAULT NULL,
  `Age` int(11) DEFAULT NULL,

替换为:

AS (DATE_SUB('1998-01-02', INTERVAL 31 DAY) STORED; 

给出类似的错误:

SQL Error [1064] [42000]: (conn=28594) You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'STORED' at line 3

但替换为:

AS (`DateExpected`) STORED; 

在用 DateExpected 的值填充 DOB 列时效果很好,所以我想这与 DATE_SUB 语句有关。

你可以这样做:

ALTER TABLE `ExampleTable`
    ADD COLUMN `DOB` DATE
    AS (`DateExpected` - INTERVAL `Age` WEEK) STORED;