5

I have channels table:

+----+-------------------+---------+
| id | sort              | bouquet |
+----+-------------------+---------+
|  1 | ["1","2","3","4"] | ["1"]   |
|  2 | ["4"]             | ["4"]   |
+----+-------------------+---------+

And need to remove "2" value from id 1 so i need to get this:

+----+-------------------+---------+
| id | sort              | bouquet |
+----+-------------------+---------+
|  1 | ["1","3","4"]     | ["1"]   |
+----+-------------------+---------+

I try using this query:

SELECT id, sort, bouquet, JSON_REMOVE(sort, '$."2"') FROM channels WHERE id=1;

But value is not removed if i use '$[2]' then value is removed but i need to remove by value not index...does anyone knows how to remove from json array specific value?

2
  • One option is to use 14.5 Prepared SQL Statement Syntax. See db-fiddle. Commented May 13, 2017 at 19:25
  • thanks it works...but i use above solution because it is more user friendly to me...but your works as expected Commented May 13, 2017 at 20:00

2 Answers 2

8

Try:

SELECT
  `id`,
  `sort`,
  `bouquet`,
  JSON_REMOVE(`sort`,
              JSON_UNQUOTE(
                JSON_SEARCH(`sort`, 'one', 2)
              ))
FROM `channels`
WHERE `id` = 1;

See db-fiddle.

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

2 Comments

I am using this JSON_REMOVE to remove a value on a JSON_COLUMn but it seems to update the column value to null if it can't find the value. Actually, in the above case when if user search for 5 shouldn't it return the original value ["1","2","3","4"]. Could you help with that??
@SarojShrestha: Try ... COALESCE(JSON_REMOVE(...), `sort`) ..., see db-fiddle.
1

Try This

UPDATE channels SET `sort` = JSON_REMOVE(`sort`, '$[1]') WHERE `id` = 1 

Working for me

1 Comment

Try `sort` = ["1","4","3","2"].

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.