MysqlJSONタイプ


前の記事-mysqlデータ型

JSONタイプ

JSONを使い始める

新しいテーブル

create table json_user ( 
uid int auto_increment, 
data json, 
primary key(uid) 
);

データを挿入

insert into json_user values ( 
null, '{
 "name":"lison", 
 "age":18,
  "address":"enjoy" 
  }' ); 
  insert into json_user values ( 
  null, '{
  "name":"james", 
  "age":28, 
  "mail":"[email protected]"
   }');

JSON関数

json_extract抽出

SELECT JSON_EXTRACT('[10, 20, [30, 40]]', '$[1]');

ここに画像の説明を挿入

select json_extract(data, '$.name'), json_extract(data, '$.address')
from json_user;

ここに画像の説明を挿入

JSON_OBJECTはオブジェクトをjsonに変換します

SELECT JSON_OBJECT("name", "enjoy", "email", "enjoy.com", "age",35);

INSERT INTO json_user VALUES ( NULL, JSON_OBJECT("name", "enjoy", "email", "enjoy.com", "age",35) );

ここに画像の説明を挿入

json_insertデータを挿入

構文:JSON_INSERT(json_doc、path、val [、path、val]…)

set @json = '{ "a": 1, "b": [2, 3]}';

select json_insert(@json, '$.a', 10, '$.c', '[true, false]');


update json_user set data = json_insert(data, "$.address_2", "xiangxue") where uid = 1;

ここに画像の説明を挿入

json_mergeはデータをマージして返します

SELECT JSON_MERGE('{"name": "enjoy"}', '{"id": 47}');

SELECT JSON_MERGE( JSON_EXTRACT(DATA, '$.address'), JSON_EXTRACT(DATA, '$.address_2')) FROM json_user WHERE uid = 1;

ここに画像の説明を挿入

その他の機能:

https://dev.mysql.com/doc/refman/5.7/en/json-function-reference.html

JSONインデックス

JSONタイプのデータ自体に直接インデックスを付けることはできません。インデックスを付ける必要のあるJSONデータの仮想列(仮想列)を再生成してから、列にインデックスを付ける必要があります。

create table test_inex_1( 
data json, 
gen_col varchar(10) generated always as (json_extract(data, '$.name')), 
index idx (gen_col) );
insert into test_inex_1(data) values ('{"name":"king", "age":18, "address":"cs"}'); 
insert into test_inex_1(data) values ('{"name":"peter", "age":28, "address":"zz"}'); 

select * from test_inex_1;
ここに画像の説明を挿入

質問:このSQLクエリの結果は何ですか?

select json_extract(data,"$.name") as username from test_inex_1 where gen_col="king";

SELECT JSON_EXTRACT(DATA、 "$。name")AS username FROM test_inex_1 WHERE gen_col = '“ king”';
ここに画像の説明を挿入

explain SELECT JSON_EXTRACT(DATA,"$.name") AS username FROM test_inex_1 WHERE gen_col="king";

ここに画像の説明を挿入

展開

公式文書を自分で確認し、仮想列を作成します。この列に記号「」を追加する必要はありません。

create table test_index_2 ( 
data json, 
gen_col varchar(10) generated always as ( json_unquote( json_extract(data, "$.name") )),
 key idx(gen_col) 
 );
insert into test_index_2(data) values ('{"name":"king", "age":18, "address":"cs"}'); 
insert into test_index_2(data) values ('{"name":"peter", "age":28, "address":"zz"}');

test_index_2からユーザー名としてjson_extract(data、 "$。name")を選択します。ここでgen_col =“ king”;
ここに画像の説明を挿入

おすすめ

転載: blog.csdn.net/weixin_42292697/article/details/114015548