我有以下 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
上面的查询返回结果如下图所示:
现在,我想用 JSON_OBJECT
替换 GROUP_CONCAT
或 换句话说,我想让 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 - Incorrect parameter count in the call to native function 'JSON_OBJECT'
最佳答案
在 ≥ 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
并且不会接受第三个参数...
≥5.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
关于MySQL JSON_OBJECT 而不是 GROUP_CONCAT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48843188/