简体   繁体   English

如何排序,mysql中的一个json_object

[英]How to order by, a json_object in mysql

I've a problem sorting a JSON_OBJECT:我在排序 JSON_OBJECT 时遇到问题:

在此处输入图像描述

How can I sort the objects as they are in the JSON OBJECT?如何对 JSON OBJECT 中的对象进行排序?

You can't control the order of the elements in the array that json_arrayagg() generates, even in MySQL 8.0, as explained in the documentation :您无法控制json_arrayagg()生成的数组中元素的顺序,即使在 MySQL 8.0 中,如文档中所述

Aggregates a result set as a single JSON array whose elements consist of the rows.将结果集聚合为单个 JSON 数组,其元素由行组成。 The order of elements in this array is undefined.此数组中元素的顺序未定义。

An ugly and not scalable work around is to use group_concat() to manually generate the json array:一个丑陋且不可扩展的解决方法是使用group_concat()手动生成 json 数组:

select 
    dashboard,
    widget,
    ...
    concat(
        '[',
        group_concat(
            json_object('color_mode', color_mode, ...)
            order by <your_ordering_clumn>
        ),
        ']'
    ) js_array
from datadog_wigets_markers 
group by dashboard, widget, ...

This will fail on long json strings.这将在长 json 字符串上失败。 I would rather try and live with json_arrayagg() and unordered arrays.我宁愿尝试使用json_arrayagg()和无序数组。

Side note: you should enumerate all the non-aggregated columns in the group by clause;旁注:您应该枚举group by子句中的所有非聚合列; it's a requirement in most databases, and a good coding practice.这是大多数数据库的要求,也是一种良好的编码习惯。

@Gordon Linoff 在这篇文章中的回答在 MySQL 8.0 上对我有用,但我没有测试它的可扩展性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM