0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

mysqlでのJsonの使い方

Last updated at Posted at 2021-11-04

メモです。

mysql でJsonを使ってみる

定義

こんな感じ

CREATE TABLE `test_table` (
	`id` CHAR(50) NOT NULL,
	`create_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
	`data` JSON NOT NULL,  <---- Json
	);

データ追加

INSERT INTO test_able (id,data) 
        VALUES ('test','{"a":"hogehoge"}')

参照

基本

select * from test_able;

json が見たい
これが使える

json_extract( Jsonのカラム ,'$.Json_key')
select json_extract(data,'$.a') from test_able;

ちょっと、どうでもいい話

Heidisql なんかでのJsonの消し方

上記のソフトでレコードを消す際、Jsonが含まれていると、消せないことがあった。
送信されている、sql を見ると消したレコードデータでJsonの中身が''で送信されていた
こんな感じ

'{"a":"test"}'

一見間違ってないように見えるけど、冷静に考えるとJsonではなく文字列として送っている?
が原因で消せなかった。(そこまで、細かく検証してないです)

Jsonデータでkeyを数字にした時

数字をキーにして保存した時、Viewを自動的に作成されなかった。
Json形式を利用して色々なViewを作成されるようにしたが、数字を考えてなかった話

結論 sqlの構文エラー
Jsonで数字のキーを扱うときは、一手間いるらしい

json_extract(json_data,'$."1"')
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?