使用JSON数据类型:MySQL 5.7及以上版本支持JSON数据类型,可以将数组转换成JSON字符串存储在该字段中。使用时可以使用JSON函数进行解析和操作。用代码怎么实现呢
时间: 2024-05-12 12:16:29 浏览: 108
创建一个表格,包括一个JSON数据类型字段:
```
CREATE TABLE mytable (
id INT PRIMARY KEY AUTO_INCREMENT,
data JSON
);
```
插入一些数据:
```
INSERT INTO mytable (data)
VALUES ('{"name": "John", "age": 30, "city": "New York"}'),
('{"name": "Jane", "age": 25, "city": "Los Angeles"}'),
('{"name": "Bob", "age": 40, "city": "San Francisco"}');
```
查询数据:
```
SELECT data->>'$.name' AS name, data->>'$.age' AS age, data->>'$.city' AS city
FROM mytable;
```
解析数组:
```
SELECT JSON_EXTRACT(data, '$.students[0].name') AS name,
JSON_EXTRACT(data, '$.students[0].age') AS age
FROM mytable;
```
更新数据:
```
UPDATE mytable
SET data = JSON_SET(data, '$.city', 'Chicago')
WHERE id = 1;
```
删除数据:
```
DELETE FROM mytable
WHERE data->>'$.city' = 'San Francisco';
```
阅读全文