如何在不干扰 FROM 子查询中的 JSON_ARRAYAGG 和 LIMIT 的情况下 return 颜色总量

How to return total amount of colors without interfering with JSON_ARRAYAGG and LIMIT in FROM subquery

产品有两种颜色(黑色和白色)

我想使用 LIMIT 来不带所有的颜色...颜色的数量就是总数


示例:

LIMIT 1 会 return:

LIMIT 2 会 return:


我要return名字,里面一个JSON

但是我看到在JSON_ARRAYAGG

中没有办法使用LIMIT

解决方案是在 FROM

中使用 子查询

有效...我必须添加 GROUP BY v.id

  • LIMIT 1 returns 只有一种颜色(OK)
  • LIMIT 2 return两种颜色(OK)

但是 颜色数量 ( amountColors ) 总是 1 以上两种情况应该是2

WITH cte AS (
    SELECT
        pdv.variation_id
    FROM product_detail pd
        INNER JOIN product_detail_variation pdv
            ON (pdv.product_detail_id = pd.id)
    WHERE pd.product_id = -- ID-HERE
)
SELECT
    JSON_ARRAYAGG(colorsName) AS colorsName,
    amountColors
FROM (
    SELECT
        JSON_OBJECT(
            'color', v.name
        ) AS colorsName,
        COUNT(v.id) AS amountColors
    FROM variation v
        INNER JOIN grid g
            ON (g.id = v.grid_id)
    WHERE g.name = 'Color' AND EXISTS (TABLE cte)
    GROUP BY v.id
    LIMIT 1
) v

/* Test: LIMIT 1
array(2) {
  ["colorsName"]=>
  string(20) "[{"color": "Black"}]"
  ["amountColors"] => int(1) // should return int(2)
}*/

/* Test: LIMIT 2
array(2) {
  ["colorsName"]=>
  string(40) "[{"color": "Black"}, {"color": "White"}]"
  ["amountColors"] => int(1) // should return int(2)
}
*/

MySQL 版本:8.0+

看看这个查询:

WITH cte AS (
    SELECT p.id p_id, p.name p_name,
           pd.id pd_id, pd.price pd_price, pd.stock pd_stock,
           pdv.id pdv_id,
           v.id v_id, v.name v_name,
           g.id g_id, g.name g_name,
           COUNT(*) OVER (PARTITION BY pd.product_id) v_count,
           ROW_NUMBER() OVER (PARTITION BY pd.product_id ORDER BY v.id) v_rn,
           JSON_OBJECT( 'color', v.name ) AS ColorName
    FROM product p
    JOIN product_detail pd ON p.id = pd.product_id
    JOIN product_detail_variation pdv ON pd.id = pdv.product_detail_id
    JOIN variation v ON v.id = pdv.variation_id
    JOIN grid g ON v.grid_id = g.id
    WHERE g.name = 'Color'
      AND pd.product_id = 1
)
SELECT p_name ProductName,
       JSON_ARRAYAGG(ColorName) AS ColorNames,
       v_count ColorsAmount
FROM cte
WHERE v_rn <= @colors_limit
GROUP BY 1, 3

fiddle

检查一下。任务的逻辑现在对我来说不是很清楚,我可能是错的...

并且我建议您扩展源数据(添加行)并再次检查(有或没有产品条件)。