SELECT
`Categories`.`id`,
`Categories`.`name`,
(
SELECT
COUNT(`id`)
FROM
`Products`
WHERE
JSON_CONTAINS(
`Products`.`category_id`,
CONCAT('"',`Categories`.`id`,'"')
)
) AS `products_count`
FROM
`Categories`
ORDER BY `products_count`
fiddle
Values in JSON have string type whereas in products table they are numbers. MySQL won't convert datatypes for JSON implicitly rather than another datatypes, because "
chars in JSON are not only datatype marks but, from MySQL looking point, they are a part of value. So add dquote chars to the value to be searched for.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…