Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL JSON_REMOVE json array

Tags:

mysql

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?

like image 277
John Avatar asked May 13 '17 18:05

John


People also ask

Can I store JSON in MySQL?

MySQL supports a native JSON data type defined by RFC 7159 that enables efficient access to data in JSON (JavaScript Object Notation) documents. The JSON data type provides these advantages over storing JSON-format strings in a string column: Automatic validation of JSON documents stored in JSON columns.

How pass JSON data to stored procedure in MySQL?

-- Stored procedure to insert post and tags DROP PROCEDURE IF EXISTS insert_post; DELIMITER $$ CREATE PROCEDURE insert_post( IN my_data JSON ) BEGIN -- Declare iterator variable to use it later on in the loop DECLARE i INT DEFAULT 0; -- Retrieve values from JSON SET @title = JSON_UNQUOTE(JSON_EXTRACT(my_data, '$.

What is Json_unquote in MySQL?

JSON_UNQUOTE() – Remove Quotes from a JSON Document in MySQL In MySQL, the JSON_UNQUOTE() function “unquotes” a JSON document and returns the result as a utf8mb4 string. You provide the JSON document as an argument, and the function will do the rest.

How do I query JSON in SQL?

You don't need a custom query language to query JSON in SQL Server. To query JSON data, you can use standard T-SQL. If you must create a query or report on JSON data, you can easily convert JSON data to rows and columns by calling the OPENJSON rowset function.


2 Answers

Try:

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

See db-fiddle.

like image 136
wchiquito Avatar answered Nov 06 '22 18:11

wchiquito


Try This

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

Working for me

like image 37
Rajshekhar Rajaharia Avatar answered Nov 06 '22 18:11

Rajshekhar Rajaharia