0

I have these records in a MySQL DB. On a JSON type column.

Record1: {"images": ["image.jpeg", "image.jpeg"]}
Record2: {"images": ["image.jpeg", "image.jpeg", "image.jpeg"]}
Record3: {"images": ["image.jpeg"]}

How can I get the total count of images by the key name of the JSON property which in my case is 'images'?

I am trying to achieve the same thing as running this below query, but counting the array items from the images key.

SELECT
  `field`,
  count( * ) AS total 
FROM
  `table_name` 
WHERE
  `condition`
GROUP BY
  `something`

which will give you this result:

field      total
------------------
field1       5
field2       2

What I am trying to achieve:

 field      total
 -----------------
 images       6

Table structure

Table structure

Table data

table data

2
  • do you want it by php or query ? Commented Dec 14, 2018 at 16:21
  • Just mysql query will be ok, thanks Commented Dec 14, 2018 at 16:41

2 Answers 2

1

Try:

SELECT
  `type`,
  SUM(
    JSON_LENGTH(`media`, '$.images')
  ) `media`
FROM
  `table_name`
GROUP BY
  `type`;

See dbfiddle.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, this is what I was after. Thank you so much!
0

ok sure You can use this query :

SELECT type,JSON_LENGTH(media) FROM `tabl4` group by type

check the execution from here : Demo

8 Comments

It is not doing what is supposed to do. I just want to get the count of all images inside the 'media->images' grouped by type.
No, 8 actually because there is the last record wich is type 1 and has 2 images
i think that what this query make check the demo to understand
I don't understand why it's not working on my local machine. Could it be because the media column is JSON type on my local? Also image.jpeg was just an example. The data will have different image names with different extensions and this query will not work with that.
ah yeh imm i think yes try to change it to varchar or text its better
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.