在 MySQL 中将默认值设置为 JSON 类型列?

mysqlmysqli database

要设置默认值,请使用 DEFAULT 约束,语法如下 −

alter table yourTableName modify column yourColumnName JSON NOT NULL DEFAULT ( JSON_OBJECT() );

让我们创建一个表 −

mysql> create table demo24
−> (
−> employee_information text
−> )
−> ;
Query OK, 0 rows affected (1.43 sec)

这是表的描述。以下是查询 −

mysql> desc demo24;

这将产生以下输出 −

+----------------------+------+------+-----+---------+-------+
| Field                | Type | Null | Key | Default | Extra |
+----------------------+------+------+-----+---------+-------+
| employee_information | text | YES  |     | NULL    |       | 
+----------------------+------+------+-----+---------+-------+
1 row in set (0.00 sec)

以下是将其更改为 JSON 数据类型的查询,默认值为 −

mysql> alter table demo24 modify column employee_information JSON NOT NULL DEFAULT ( JSON_OBJECT() );
Query OK, 0 rows affected (3.03 sec)
Records: 0 Duplicates: 0 Warnings: 0

现在检查表的描述。以下是查询 −

mysql> desc demo24;

这将产生以下输出 −

+----------------------+------+------+-----+---------------+-------------------+
| Field                | Type | Null | Key | Default       | Extra             |
+----------------------+------+------+-----+---------------+-------------------+
| employee_information | json | NO   |     | json_object() | DEFAULT_GENERATED |
+----------------------+------+------+-----+---------------+-------------------+
1 row in set (0.00 sec)

使用 insert 命令向表中插入一些记录 −

mysql> insert into demo24 values();;
Query OK, 1 row affected (0.10 sec)

使用 select 语句显示表中的记录 −

mysql> select *from demo24;

这将产生以下输出 −

+----------------------+
| employee_information |
+----------------------+
| {}                   |
+----------------------+
1 row in set (0.00 sec)

相关文章


有用资源