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?

MySQLのJSON型の特定要素の更新

Posted at

JSON型の特定要素のみの更新についてのメモ

■準備

jsonを持つテーブルを用意

CREATE TABLE `test` (
   `col` JSON NULL DEFAULT NULL
);
INSERT INTO test (col) values (null);

■UPDATE分

testテーブルのcolカラムのkey1という要素を更新

UPDATE test SET
 col = JSON_SET(
   IFNULL(col, '{"key1":null}'),
   '$.key1',
   CAST('[{"name":"なまえ1","text":"テキスト1"}]' AS JSON)
 )

JSON_SETnullの場合、値の設定が出来ません。
その為、IFNULLを使用してnullの場合にデフォルト値を使用するようにしています。

json文字列を設定する場合、CASTが必要になります。
json文字列を直接記述していますが、JSON_OBJECTを使用することも可能です。
※プログラムで文字列を生成することを考えています。

■PHPから更新

testテーブルのcolカラムのkey1という要素を更新

// SQL文字列を作成
$sql = sprintf(
    'UPDATE test SET col = JSON_SET(IFNULL(col, \'%s\'), \'$.key1\', CAST(\'%s\' AS JSON))',
    json_encode(['key1' => null]),
    json_encode(['name' => 'テスト'], JSON_UNESCAPED_UNICODE),
);
// SQLを実行
...

IFNULLのデフォルト値は(複数)階層になりますので、json_encodeで配列を渡しています。
設定値のjson_encodeJSON_UNESCAPED_UNICODEは設定しないとエスケープされます。

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?