Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.9k 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...