Reputation: 1117
I have the following table of data
What I am trying to do is GROUP BY
timestamp and JSON_MERGE
the objects. What I expect as a result is the following.
I expected the following query to work but I just get an error
SELECT timestamp, JSON_MERGE(json)
FROM data
GROUP BY timestamp, JSON_MERGE(json)
The error I am getting is
Incorrect parameter count in the call to native function 'JSON_MERGE'
Upvotes: 0
Views: 4150
Reputation: 1391
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:
JSON_MERGE()
, for example:
{}
. This might change in future versions
of the server.Upvotes: 2