Mysql5.7.9原生JSON格式支持php
建立表sql
create table news (uid int auto_increment, data json, primary key(uid))engine innodb;
插入數據json
insert into news values (NULL,'{"name":"tester","mail":"test@gmail.com","address":"Shangahai"}')
插入數據不是Json格式,會報如下錯函數
insert into news values(NULL,'test'); Error Code: 3140.Invalid JSON text: "Invalid value." at position 1 in value (or column) 'test'
新內置函數,高效地處理JSON字符,不須要遍歷全部數據查找。
ui
select json_extract(data, '$.name'),json_extract(data,'$.address') from news where json_extract(data, '$.name') = 'David';
虛擬列功能,經過傳統的B+樹索引便可實現對JSON格式部分屬性的快速查詢
code
加虛擬列索引
ALTER TABLE user ADD user_name varchar(50) GENERATED ALWAYS AS (json_extract(data,'$.name')) VIRTUAL;
加索引rem
alter table user add index idx_username (user_name);
和普通列查詢同樣
it
select * from user where user_name='David'