天天看點

使用mysql的merge_mysql中json_merge函數的使用?

需求描述:

通過mysql中的json_merge函數,可以将多個json對象合并成一個對象

操作過程:

1.檢視一張包含json列的表

mysql> select * from tab_json;

+----+-----------------------------------------------------------------------------------+

| id | data |

+----+-----------------------------------------------------------------------------------+

| 1 | {"Tel": "132223232444", "name": "david", "address": "Beijing"} |

| 2 | {"Tel": "13390989765", "name": "Mike", "address": "Guangzhou"} |

| 3 | {"names": "Smith"} |

| 4 | {"names": "Smith", "address": "Beijing"} |

| 5 | {"names": "Smith", "address": "Beijing", "birthday": "2018-09-09"} |

| 6 | {"Max": "true", "names": "Smith", "address": "Beijing", "birthday": "2018-09-09"} |

| 7 | {"max": "true", "names": "Smith", "address": "Beijing", "birthday": "2018-09-09"} |

| 8 | {"oax": "true", "names": "Smith", "address": "Beijing", "birthday": "2018-09-09"} |

+----+-----------------------------------------------------------------------------------+

8 rows in set (0.00 sec)

2.将names的值與address的值進行合并

mysql> select json_extract(data,'$.names'),json_extract(data,'$.address') from tab_json;

+------------------------------+--------------------------------+

| json_extract(data,'$.names') | json_extract(data,'$.address') |

+------------------------------+--------------------------------+

| NULL | "Beijing" |

| NULL | "Guangzhou" |

| "Smith" | NULL |

| "Smith" | "Beijing" |

| "Smith" | "Beijing" |

| "Smith" | "Beijing" |

| "Smith" | "Beijing" |

| "Smith" | "Beijing" |

+------------------------------+--------------------------------+

8 rows in set (0.00 sec)

mysql> select json_merge(json_extract(data,'$.names'),json_extract(data,'$.address')) from tab_json;

+-------------------------------------------------------------------------+

| json_merge(json_extract(data,'$.names'),json_extract(data,'$.address')) |

+-------------------------------------------------------------------------+

| NULL |

| NULL |

| NULL |

| ["Smith", "Beijing"] |

| ["Smith", "Beijing"] |

| ["Smith", "Beijing"] |

| ["Smith", "Beijing"] |

| ["Smith", "Beijing"] |

+-------------------------------------------------------------------------+

8 rows in set (0.00 sec)

3.如果多個對象含有相同的key,那麼也會進行合并為具體的values

mysql> SELECT JSON_MERGE('{"a": 1, "b": 2}', '{"c": 3, "a": 4}');

+----------------------------------------------------+

| JSON_MERGE('{"a": 1, "b": 2}', '{"c": 3, "a": 4}') |

+----------------------------------------------------+

| {"a": [1, 4], "b": 2, "c": 3} |

+----------------------------------------------------+

1 row in set (0.00 sec)

備注:将兩個對象的值合并成一個,a這個key的值也增加到了2個.

文檔建立:2018年6月6日17:49:18