MySQL JSON_OBJECT而不是GROUP_CONCAT

时间:2018-02-17 16:03:47

标签: mysql sql json mysql-5.7

我有以下sql查询使用GROUP_CONCAT正常工作:

JSON_OBJECT

以上查询返回的结果如下图所示:

enter image description here

现在,我想将prop替换为SELECT orders.created_at,products.title, o_p.qty AS qty, JSON_OBJECT((SELECT GROUP_CONCAT("title",features.title,"value", o_p_f.value, 'unit',features.unit) FROM order_product_features AS o_p_f LEFT JOIN product_features ON product_features.id = o_p_f.product_feature_id LEFT JOIN features ON o_p_f.product_feature_id = product_features.id AND features.id = product_features.feature_id WHERE o_p_f.order_product_id = o_p.id )) AS prop FROM orders LEFT JOIN order_products AS o_p ON o_p.order_id = orders.id LEFT JOIN products ON products.id = o_p.product_id ,换句话说,我希望将namespace A; class classOne{ public function methodOne(){} public function methodTwo(){} public function classOne(){} //Constructor } class classTwo{ public function methodOne(){} public function methodTwo(){} public function classTwo(){} //Constructor } 字段替换为JSON对象。我尝试过以下方法:

classOne()

但是,上面的查询返回错误:

  

1582 - 调用本机函数时参数计数不正确' JSON_OBJECT'

1 个答案:

答案 0 :(得分:7)

开≥5.7.22

JSON_OBJECTAGG(key, value)更有可能是您追求的目标。

mysql> SELECT o_id, attribute, value FROM t3;
+------+-----------+-------+
| o_id | attribute | value |
+------+-----------+-------+
|    2 | color     | red   |
|    2 | fabric    | silk  |
|    3 | color     | green |
|    3 | shape     | square|
+------+-----------+-------+
4 rows in set (0.00 sec)

mysql> SELECT o_id, JSON_OBJECTAGG(attribute, value) FROM t3 GROUP BY o_id;
+------+----------------------------------------+
| o_id | JSON_OBJECTAGG(attribute, name)        |
+------+----------------------------------------+
|    2 | {"color": "red", "fabric": "silk"}     |
|    3 | {"color": "green", "shape": "square"}  |
+------+----------------------------------------+
1 row in set (0.00 sec)

但是,由于您没有提供表格结构,我无法帮助您进行查询。

似乎你对unit的处理会给你一些额外的工作,因为聚合函数使用Key=>Value而不会采取第三个参数......

开≥7.7

你必须做一些手工艺:

SELECT 
o_id, 
CONCAT(
    '{', 
    GROUP_CONCAT(
        TRIM(
            LEADING '{' FROM TRIM(
                TRAILING '}' FROM JSON_OBJECT(
                    `attribute`, 
                    `value`
                    )
                )
            )
        ),
    '}'
    ) json 
FROM t3 
GROUP BY o_id

≥5.5

没有任何JSON功能:

SELECT 
o_id, 
CONCAT(
    '{', 
    GROUP_CONCAT(
        CONCAT(
            '"',
            `attribute`,
            '":"',
            `value`,
            '"'
            )
        ),
    '}'
    ) json 
FROM t3 
GROUP BY o_id