2016-11-10 175 views
1

我有數據MYSQL JSON_MERGE和GROUP BY

enter image description here

我所試圖做的是GROUP BY時間戳和JSON_MERGE對象如下表所示。我期望的結果如下。

enter image description here

我希望下面的查詢工作,但我只是得到一個錯誤

SELECT timestamp, JSON_MERGE(json) 
FROM data 
GROUP BY timestamp, JSON_MERGE(json) 

我得到的錯誤是在調用本地函數

不正確的參數個數'JSON_MERGE'

回答

1

使用字符串函數組裝所需的JSON,然後將其轉換爲JSON。

實施例數據

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'); 

查詢合併所有json值由時間戳分組

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; 

查詢結果

+------------------+---------------------+ 
| json    | timestamp   | 
|------------------+---------------------| 
| {"a": 1, "b": 2} | 2016-10-01 00:00:00 | 
| {"c": 3}   | 2016-10-01 11:11:11 | 
+------------------+---------------------+ 

若干注意事項:

  • 這個片段的行爲是從JSON_MERGE()不同,例如:
    • 當兩個或多個屬性具有相同的名稱及其值是 覆蓋,而不是被合併到值數組
    • 它不能合併對象與陣列
  • 作爲介紹的解決方案僅適用於對象作爲頂級實體 而不是數組。可以修改它以處理數組。
  • 如果依賴於以JSON對象開頭的字符串表示形式,並且以大括號{}結尾的 。這可能會在服務器的將來版本 中更改。