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] $って何?

Posted at

結論

json型のカラムの中身を表示したりする時に使う

手順

テーブル作成

mysql> CREATE TABLE json_tests (json JSON);
mysql> SHOW COLUMNS FROM json_tests;
/** 出力
+-------+------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+------+------+-----+---------+-------+
| json  | json | YES  |     | NULL    |       |
+-------+------+------+-----+---------+-------+
1 row in set (0.01 sec)
*/

レコード作成

mysql> INSERT INTO json_tests
VALUES
('{"name": "A", "options": {"x": 100, "y": [100, 200, 300]}}'),
('{"name": "B", "options": {"x": 100, "y": [100]}}'),
('{"name": "C", "options": {"x": 100, "y": [100, 200]}}');

mysql> SELECT * FROM json_tests;
/** 出力
+------------------------------------------------------------+
| json                                                       |
+------------------------------------------------------------+
| {"name": "A", "options": {"x": 100, "y": [100, 200, 300]}} |
| {"name": "B", "options": {"x": 100, "y": [100]}}           |
| {"name": "C", "options": {"x": 100, "y": [100, 200]}}      |
+------------------------------------------------------------+
3 rows in set (0.00 sec)
*/

jsonの中身をSELECTしてみる

mysql> SELECT json->"$.name" FROM json_tests;
/** 出力
+----------------+
| json->"$.name" |
+----------------+
| "A"            |
| "B"            |
| "C"            |
+----------------+
*/

配列の中はこんな感じ

/** [] は数字添字で0から始まる */
mysql> SELECT json->"$.options.y[1]" FROM json_tests;
/** 出力
+------------------------+
| json->"$.options.y[1]" |
+------------------------+
| 200                    |
| NULL                   |
| 200                    |
+------------------------+
3 rows in set (0.00 sec)
*/

まとめ

$はjson型のカラムの中をSELECTする時に使う。
他の使い道はわからないのでわかったら追記する。(予定)

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?