Assemble desired JSON using string functions and then cast it into JSON.
Example data
create table data (json json, timestamp datetime);
insert into data values
('{"a": 1}', '2016-10-01 00:00:00'),
('{"b": 2}', '2016-10-01 00:00:00'),
('{"c": 3}', '2016-10-01 11:11:11'),
('{}', '2016-10-01 11:11:11'),
('{"c": 33}', '2016-10-01 11:11:11');
Query to merge all json
values grouped by timestamp
select cast(
concat('{', -- wrap everything in root object '{ ... }'
group_concat(
-- strip parenthesis from individual item representation
-- '{"foo": 1}' -> '"foo": 1'
substring(json, 2, length(json) - 2)),
'}') as json) json,
timestamp
from data
-- skip empty JSON values to avoid getting extra comma during
-- group_concat
where json != JSON_OBJECT()
group by timestamp;
Query result
+------------------+---------------------+
| json | timestamp |
|------------------+---------------------|
| {"a": 1, "b": 2} | 2016-10-01 00:00:00 |
| {"c": 3} | 2016-10-01 11:11:11 |
+------------------+---------------------+
Several caveats:
- Behaviour of this snippet is different from
JSON_MERGE()
, for example:
- When two or more properties have the same name their values are
overwritten instead of being merged into array of values
- It can't merge objects with arrays
- Solution as presented only works with objects as a top level entity
and not with arrays. It can be modified to work with arrays.
- If relies on string representation of JSON objects beginning and
ending with curly brackets
{}
. This might change in future versions
of the server.