【发布时间】:2018-02-17 16:03:47
【问题描述】:
我有以下 sql 查询,使用 GROUP_CONCAT 可以正常工作:
SELECT orders.created_at,products.title, o_p.qty AS qty,
(SELECT GROUP_CONCAT(features.title,"\:", o_p_f.value, 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
以上查询返回结果如下图所示:
现在,我想将GROUP_CONCAT 替换为JSON_OBJECT 或换句话说,我想让prop 字段成为JSON 对象。我尝试了以下方法:
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
但是,上面的查询返回错误:
1582 - 调用本机函数“JSON_OBJECT”时的参数计数不正确
【问题讨论】:
-
@Blag 简单地说,正如我在问题“......或者换句话说,我想让
prop字段成为 JSON 对象”,即我需要一种方法来转换道具字段转换为 JSON 对象。您将提供的任何使用GROUP_CONCAT的示例,然后使用任何方式将该连接的字符串转换为 JSON 都足以解决我的问题。 -
请提供一些测试数据和您的创建表,没有...
-
根据docs,JSON_OBJECT 接受偶数个参数,对应于key1、value1、key2、value2 等。你传递给它一个参数,即GROUP_CONCAT 返回的字符串。跨度>
-
我会尝试消除对 group_concat 的调用。您似乎没有 group by 子句,所以我想知道您为什么要使用 group_concat 而不是 concat。我认为 json_object(select “title”, features.title, “value”, ...etc) 将是要走的路。