在mysql中,如何删除json数组中不包含某些字符串值元素?

abithluo  于 2023-04-05  发布在  Mysql
关注(0)|答案(1)|浏览(264)

我有一个表,其中有一列jsons,这些jsons具有示例值:

{"name": "1", "list": ["abc", "xyz"]}
{"name": "2", "list": ["b", "bc", "bcd"]}
{"name": "3", "list": ["cd", "cdef", "def", "defg", "ef"]}

我也有一个数组(子)字符串,我想在数组中保留,例如:
["a","bc","def"]
(in我的现实,约20字符串)
如何更新表,使列表中只保留至少包含其中一个字符串的元素?
预期结果:

{"name": "1", "list": ["abc"]}
{"name": "2", "list": ["bc", "bcd"]}
{"name": "3", "list": ["cdef", "def", "defg"]}

老实说,我甚至不知道从哪里开始,甚至不知道在SQL及其JSON函数中是否可能。

wecizke3

wecizke31#

Here就是一个例子。我们的想法是从list数组中拆分值,并使用REGEXP检查匹配。然后构建只包含匹配元素的新list数组。之后,更新原始表。

CREATE TABLE DataSource 
( 
    id INT AUTO_INCREMENT PRIMARY KEY
   ,RawData JSON
);

INSERT INTO DataSource (RawData) VALUES 
    ('{"name": "1", "list": ["abc", "xyz"]}'),
    ('{"name": "2", "list": ["b", "bc", "bcd"]}'),
    ('{"name": "3", "list": ["cd", "cdef", "def", "defg", "ef"]}');

SET @keepList = '["a","bc","def"]';
SET @keepList = REPLACE(REPLACE(REPLACE(REPLACE(@keepList, '[', ''), ']', ''), ',', '|'), '"', '');

WITH NewDataSource (ID, name, value) AS
(
      SELECT DS.ID
            ,JSON_EXTRACT(DS.RawData, '$.name')
            ,JSON_ARRAYAGG(j.value)
      FROM DataSource DS,
      JSON_TABLE(DS.RawData, '$.list[*]' COLUMNS (value VARCHAR(255) PATH '$')) AS j
      WHERE j.value REGEXP  @keepList
      GROUP BY DS.ID
              ,JSON_EXTRACT(DS.RawData, '$.name')
 ) 
UPDATE DataSource T
INNER JOIN NewDataSource S
    ON T.id = S.id
SET T.RawData = JSON_OBJECT
               (
                  'name', S.name
                 ,'list', S.value
               );
               
SELECT *
FROM DataSource;

相关问题