A
A
agent_22032021-08-22 17:54:38
MySQL
agent_2203, 2021-08-22 17:54:38

How to remove a tuple from an array by the value of the tuple?

There is a following line in the table

+---+----------------------+
| id | sort
+---+----------------------+
| 1 | [12, 13, {"12": 123} ]
+---+----------------------+

How can I remove the element {"12": 123} without knowing its index in the array, but knowing the tuple itself ?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Akina, 2021-08-23
@agent_2203

Divide into elements, discard unnecessary, collect back:

WITH cte AS (SELECT 1 id, CAST('[12, 13, {"12": 123} ]' AS JSON) sort)
SELECT cte.id, JSON_ARRAYAGG(jsontable.element) sort
FROM cte
CROSS JOIN JSON_TABLE(cte.sort,
                      '$[*]' COLUMNS (element JSON PATH '$')) jsontable
WHERE jsontable.element != CAST('{"12": 123}' AS JSON)
GROUP BY cte.id

https://dbfiddle.uk/?rdbms= mysql_8.0 &fiddle=405ff0... Comparing JSON objects is a thankless task. In more complex cases, it will not work, even JSON_OVERLAPS () may not save. Perhaps using string functions on a JSON string representation is a better solution.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question