从 MySQL 5.7.8 开始,MySQL 支持原生的 JSON 数据类型。
创建 JSON
类似 varchar,设置 JSON 主要将字段的 type 是 json, 不能设置长度,可以是 NULL 但不能有默认值。
mysql> CREATE TABLE lnmp (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`category` JSON,
`tags` JSON,
PRIMARY KEY (`id`)
);
mysql> DESC lnmp;
+----------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+------------------+------+-----+---------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| category | json | YES | | NULL | |
| tags | json | YES | | NULL | |
+----------+------------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)
这样 JSON 的字段就创建好了。
插入 JSON
就是插入 json 格式的字符串,可以是对象的形式,也可以是数组的形式
mysql> INSERT INTO `lnmp` (category, tags) VALUES ('{"id": 1, "name": "lnmp.cn"}', '[1, 2, 3]');
Query OK, 1 row affected (0.01 sec)
MySQL 也有专门的函数 JSON_OBJECT,JSON_ARRAY 生成 json 格式的数据
mysql> INSERT INTO `lnmp` (category, tags) VALUES (JSON_OBJECT("id", 2, "name", "php.net"), JSON_ARRAY(1, 3, 5));
Query OK, 1 row affected (0.00 sec)
查看插入的数据
mysql> SELECT * FROM lnmp;
+----+------------------------------+-----------+
| id | category | tags |
+----+------------------------------+-----------+
| 1 | {"id": 1, "name": "lnmp.cn"} | [1, 2, 3] |
| 2 | {"id": 2, "name": "php.net"} | [1, 3, 5] |
+----+------------------------------+-----------+
2 rows in set (0.00 sec)
查询 JSON
查询 json 中的数据用 column->path的形式,其中对象类型 path 这样表示 $.path, 而数组类型则是 $[index]
mysql> SELECT id, category->'$.id', category->'$.name', tags->'$[0]', tags->'$[2]' FROM lnmp;
+----+------------------+--------------------+--------------+--------------+
| id | category->'$.id' | category->'$.name' | tags->'$[0]' | tags->'$[2]' |
+----+------------------+--------------------+--------------+--------------+
| 1 | 1 | "lnmp.cn" | 1 | 3 |