简体   繁体   English

从 JSON_OBJECT 按值排序 mysql 结果

[英]Order mysql result by value from JSON_OBJECT

I have MariaDB 10.2 and this SQL:我有 MariaDB 10.2 和这个 SQL:

SELECT products.*,
  CONCAT('[', GROUP_CONCAT(JSON_OBJECT(
  'id', V.id,
  'price', V.price
  ) ORDER BY V.price ASC), ']') AS variants,
FROM products
LEFT JOIN products_variants V ON V.products_id = products.id
GROUP BY products.id
LIMIT 0,10

Result is:结果是:

Array (
  [0] => Array (
    [id] => 1,
    [variants] => [{"id": 1, "price": 100},{"id": 2, "price": 110}]
  )
  [1] => Array (
    [id] => 2,
    [variants] => [{"id": 3, "price": 200},{"id": 4, "price": 210}]
  )
)

I need to sort the products according to the price of the first variation of each product.我需要根据每个产品的第一个变体的价格对产品进行排序。

  • Product id 1 must be the first because the first variant price is 100产品 ID 1 必须是第一个,因为第一个变体价格是 100
  • Product id 2 must be the second because the first variant price is 200 and 200 > 100产品 ID 2 必须是第二个,因为第一个变体价格是 200 并且 200 > 100

I try:我尝试:

ORDER BY JSON_EXTRACT(`variants`, '$[0].price)

but get error:但得到错误:

Reference 'variants' not supported (reference to group function)

I think you want:我想你想要:

order by min(v.price)

There is no need to parse the JSON object.无需解析 JSON 对象。

This is an example of when one should not hide a column ( price ) inside a column (in JSON, in this case).这是一个不应在列中隐藏列 ( price ) 的示例(在本例中为 JSON)。 Instead, keep price as its own column to make it simple for MySQL to access for sorting (as you needed) or filtering.取而代之的是,将price作为自己的列,以便 MySQL 可以轻松访问以进行排序(根据需要)或过滤。

It is OK to also keep the column inside the JSON string, so that the JSON is "complete".也可以将列保留在JSON字符串中,以便 JSON 是“完整的”。

The problem was that you had the wrong quotes around variant .问题是你在variant周围有错误的引号。 Backtics (which you used) is for column and table names. Backtics(您使用的)用于列名和表名。 You needed apostrophes or double-quotes ( ' or " ) because variant is just a string in this context.)您需要撇号或双引号( '" ),因为variant在此上下文中只是一个字符串。)

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

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