32

I have table channels:

+----+----------------+---------+
| id | sort           | bouquet |
+----+----------------+---------+
|  1 | ["2","3","73"] | ["1"]   |
| 12 | ["3","73"]     | ["28"]  |
+----+----------------+---------+

And need to get count items in sort field for specific boquet...for example:

bouquet 1 have 3 sort items bouquet 12 have 2 sort items

I try using this query in mysql but i did not get idea how can i calculate number of items in sort field:

SELECT COUNT(sort) AS total_channels 
FROM channels 
WHERE JSON_SEARCH(bouquet, 'one', "1") IS NOT NULL;

I always get:

+----------------+
| total_channels |
+----------------+
|              1 |
+----------------+

Which is incorrect.

6
  • 5
    Have you read about JSON_LENGTH()? Commented Aug 30, 2017 at 17:17
  • Using SELECT JSON_LENGTH(bouquet) FROM channels; i get 1 as result Commented Aug 30, 2017 at 17:18
  • 2
    Then try SELECT JSON_LENGTH(sort) FROM channels; Commented Aug 30, 2017 at 17:19
  • Yes i forget to put sort now it returns correct count values but can you please write here how to put WHERE bouquet="1"? bouqet is json type ["1"] so i can'not use bouquet="1" Commented Aug 30, 2017 at 17:22
  • There is another function JSON_DEPTH() .... see if that helps. Commented Aug 30, 2017 at 17:23

2 Answers 2

58

Using above help i come to this:

SELECT JSON_LENGTH(sort) FROM channels WHERE bouquet='["1"]';

And i get correct count:

mysql> SELECT JSON_LENGTH(sort) FROM channels WHERE bouquet='["28"]';
+-------------------+
| JSON_LENGTH(sort) |
+-------------------+
|                 2 |
+-------------------+
1 row in set (0.00 sec)
Sign up to request clarification or add additional context in comments.

Comments

1

JSON_LENGTH(sort) is wrong way

for example your table contains:

+----+----------------+---------+
| id | sort           | bouquet |
+----+----------------+---------+
|  1 | ["2","3","73"] | ["1"]   |
|  2 | NULL           | ["33"]   |
| 12 | ["3"]          | ["28"]  |
+----+----------------+---------+

and SELECT JSON_LENGTH(sort) will return this result

+----+----------------+---------+
3
1
1
+----+----------------+---------+

Comments

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.