0

I'm managing a followers list through a JSON array. I'm using JSON_ARRAY_APPEND to add a follower:

UPDATE users 
SET follows = JSON_ARRAY_APPEND(follows, '$', "followerToBeAdded") 
WHERE username = "user"

However, I'm unable to remove a follower from this list. If I try JSON REMOVE, it just erases the whole JSON array instead of just removing a particular follower from the list.

Any idea of a possible query for it?

3
  • Are you using mariaDB or MySQL? Commented Sep 9, 2021 at 2:44
  • Provide sample data as CREATE TABLE + INSERT INTO scripts and desired final data state for it. Specify precise DBMS version. Commented Sep 9, 2021 at 4:51
  • @4EACH MySQL. Harry's query worked perfectly (accepted it as an answer to the question). Commented Sep 9, 2021 at 4:56

1 Answer 1

1

As you've added the MySQL tag in the question so the following response is inaccordance with MySQL.

Let's consider the users table with the two columns username and json column follows. Assume we've a username x and one follower a to begin with.

Let's add 2nd and 3rd follower

UPDATE users SET follows = JSON_ARRAY_APPEND(follows, '$', 'b') where username ='x';
UPDATE users SET follows = JSON_ARRAY_APPEND(follows, '$', 'c') where username ='x';

Removal: Let's say we want to remove the follower b To check the follower to be removed

SELECT JSON_SEARCH(follows, 'one', 'b')  FROM users;

Above will give path to the object to be deleted in the array.

UPDATE users SET follows = JSON_REMOVE(follows, JSON_UNQUOTE(JSON_SEARCH(follows, 'one', 'b'))) WHERE JSON_SEARCH(follows, 'one', 'b') IS NOT NULL;
Sign up to request clarification or add additional context in comments.

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.