Mysql Json聚合操作

501 阅读1分钟

JSON_OBJECT 操作



mysql> SELECT JSON_OBJECT('id', 87, 'name', 'carrot'); 
+-----------------------------------------+ 
| JSON_OBJECT('id', 87, 'name', 'carrot') | 
+-----------------------------------------+ 
| {"id": 87, "name": "carrot"}            | 
+-----------------------------------------+


mysql> SELECT JSON_OBJECT('key1', 1, 'key2', 'abc', 'key1', 'def'); 
+------------------------------------------------------+ 
| JSON_OBJECT('key1', 1, 'key2', 'abc', 'key1', 'def') | 
+------------------------------------------------------+ 
| {"key1": 1, "key2": "abc"}                           | 
+------------------------------------------------------+

JSON_ARRAY 操作


mysql> SELECT JSON_ARRAY(1, "abc", NULL, TRUE, CURTIME()); 
+---------------------------------------------+ 
|JSON_ARRAY(1, "abc", NULL, TRUE, CURTIME())  |
+---------------------------------------------+
|[1, "abc", null, true, "11:30:24.000000"]    |
+---------------------------------------------+

JSON_ARRAYAGG 操作


mysql> SELECT o_id, attribute, value FROM t3; 
+------+-----------+-------+ 
| o_id | attribute | value | 
+------+-----------+-------+ 
| 2    | color     | red   | 
| 2    | fabric    | silk  | 
| 3    | color     | green | 
| 3    | shape     | square| 
+------+-----------+-------+ 
4 rows in set (0.00 sec) 

mysql> SELECT o_id, JSON_ARRAYAGG(attribute) AS attributes -> FROM t3 GROUP BY o_id; 
+------+---------------------+ 
| o_id | attributes          | 
+------+---------------------+ 
| 2    | ["color", "fabric"] | 
| 3    | ["color", "shape"]  | 
+------+---------------------+ 
2 rows in set (0.00 sec)

JSON_OBJECTAGG 操作

mysql> SELECT o_id, attribute, value FROM t3; 
+------+-----------+-------+ 
| o_id | attribute | value | 
+------+-----------+-------+ 
| 2    | color     | red   | 
| 2    | fabric    | silk  | 
| 3    | color     | green | 
| 3    | shape     | square| 
+------+-----------+-------+ 
4 rows in set (0.00 sec) 

mysql> SELECT o_id, JSON_OBJECTAGG(attribute, value) -> FROM t3 GROUP BY o_id; 

+------+---------------------------------------+ 
| o_id | JSON_OBJECTAGG(attribute, value)      | 
+------+---------------------------------------+ 
| 2    | {"color": "red", "fabric": "silk"}    | 
| 3    | {"color": "green", "shape": "square"} | 
+------+---------------------------------------+ 

2 rows in set (0.00 sec)