LoginSignup
4
3

More than 5 years have passed since last update.

MySQL の Json array型変数から要素を分解しテーブル作成

Last updated at Posted at 2016-06-28

こんにちは。
MySQL の Json の array型変数から要素を分解しテーブルを作ってみました(縦に並べ替え)1 2。ただし実行効率が悪く実用性は疑問です。

set @jarr = json_array(json_array(0), json_array(1,2), json_array(3,4,5));
set @jarr_len = json_length(@jarr);
select @jarr as json_array;
+--------------------------+
| json_array               |
|--------------------------|
| [[0], [1, 2], [3, 4, 5]] |
+--------------------------+

set @i = -1;
PREPARE SET_STMT FROM 'SELECT JSON_EXTRACT(@jarr, concat("$[", (@i:=@i+1), "]")) as json_array_unnested from my_tall_table limit ?';
EXECUTE SET_STMT USING @jarr_len;
+-----------------------+
| json_array_unnested   |
|-----------------------|
| [0]                   |
| [1, 2]                |
| [3, 4, 5]             |
+-----------------------+

上記では、既存のテーブル my_tall_table が事前に存在していると仮定しています。このようなテーブルを作る方法例は、

CREATE TABLE my_tall_table (id int) ENGINE=MyISAM;
INSERT INTO my_tall_table (id) VALUES (0);
INSERT INTO my_tall_table (id) SELECT 0 FROM my_tall_table; // これを複数繰り返してレコード数を増やす

SELECT CASE WHEN COUNT(*) >= @jarr_len THEN 'true' ELSE 'false' END as 'height(my_tall_table) >= @jarr_len' FROM my_tall_table
+------------------------------------+
| height(my_tall_table) >= @jarr_len |
|------------------------------------|
| true                               |
+------------------------------------+



  1. MySQL の検索結果を Json array型にする方法」の逆に当たります。 

  2. なお、Postgresql は、これを行うための unnest()関数を持っているそうです(PostgreSQLのあまり知られていない型3種)。 

4
3
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
4
3