Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.8k views
in Technique[技术] by (71.8m points)

mariadb - MySQL how to search JSON Array or JSON_CONTAINS in where statement with column name

I am currently using MySQL 5.7. Products table contains a column to store category ids. These ids are stored in a JSON string. I am looking for the most efficient method to count the numbers of products in each categories.

I have the following categories and products tables

Categories:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...