添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

如何在MySQL中创建一个生成列 "年龄",从列 "生日 "计算 "年龄"?

0 人关注

这里是我的sql。

create table student(
    id smallint primary key auto_increment,
    class_id smallint not null ,
    name varchar(10) not null ,
    birthday date not null ,
    sex bool not null ,
    age int as (to_days(now()-birthday))
[2022-04-10 12:08:42] [HY000][3763] Expression of generated column 'age' contains a disallowed function: now.
[2022-04-10 12:08:42] [HY000][3763] Expression of generated column 'age' contains a disallowed function: now.

我搜索了一下资料,了解到像now()这样返回值不确定的函数不能用于计算列表达式。我应该如何实现生日列的计算?

1 个评论
最好的办法是只存储生日值,在视图中进行年龄计算。
mysql
sql
database
TPam
TPam
发布于 2022-04-10
1 个回答
user3733831
user3733831
发布于 2022-04-18
0 人赞同

在创建表时不要使用 age 列。你可以在查询时找到年龄,如下图所示。

SELECT TIMESTAMPDIFF(YEAR, birthday ,CURDATE()) as age 
FROM student

你也可以查看这个问题和答案

是的,你可以通过使用MySQL生成的列来做到这一点,所以你必须重新创建学生表,如下所示。

CREATE TABLE student 
    id smallint primary key auto_increment,
    class_id smallint not null ,
    name varchar(45) not null ,
    birthday date not null ,
    sex bool not null ,
    age int GENERATED ALWAYS AS (TIMESTAMPDIFF(YEAR, birthday ,CURDATE()))

为了测试age列,你必须在student表中insert一行,像这样。

INSERT INTO student (class_id, name, birthday, sex) 
VALUES ('A001', 'Student Name', '1983-02-05', 1);
+----+----------+--------------+------------+-----+------+