You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MySQL中如何将test表title列值转为类数组字符串并更新tags列

实现title转类数组字符串并更新tags列的SQL语句

由于不同数据库的字符串处理函数差异较大,以下针对主流数据库分别提供实现方案:

MySQL/MariaDB

通过正则表达式匹配目标多词短语和单个词,替换为带引号的格式后组装成类数组字符串:

UPDATE test
SET tags = CONCAT(
    '[ ',
    REGEXP_REPLACE(
        REGEXP_REPLACE(title, '(dual sim|not activated|[a-z0-9]+)', '\"$1\"'),
        '\s+', ' , '
    ),
    ' ]'
)
WHERE tags IS NULL OR tags = '';

注意:需将业务中需要作为单个元素的多词短语(如dual sim、not activated)补充到正则表达式的匹配规则中,确保这些短语被识别为整体。

PostgreSQL

利用regexp_matches提取所有目标元素,再通过string_agg组装成类数组格式:

UPDATE test
SET tags = CONCAT('[ ', sub.tags_str, ' ]')
FROM (
    SELECT 
        id,
        string_agg('"' || elem || '"', ' , ') AS tags_str
    FROM test
    CROSS JOIN regexp_matches(title, 'dual sim|not activated|[a-z0-9]+', 'g') AS matches(elem)
    WHERE tags IS NULL OR tags = ''
    GROUP BY id
) AS sub
WHERE test.id = sub.id;

说明:regexp_matches的第三个参数g表示全局匹配,会提取所有符合规则的元素,适合批量处理多词短语和单个词。

SQL Server

先将多词短语替换为无空格的临时标记,分割后再还原,最后组装成目标格式:

WITH processed_title AS (
    SELECT 
        id,
        REPLACE(REPLACE(title, 'dual sim', 'dual_sim'), 'not activated', 'not_activated') AS temp_title
    FROM test
    WHERE tags IS NULL OR tags = ''
),
split_elements AS (
    SELECT 
        id,
        REPLACE(REPLACE(value, 'dual_sim', 'dual sim'), 'not_activated', 'not activated') AS elem
    FROM processed_title
    CROSS APPLY STRING_SPLIT(temp_title, ' ')
    WHERE value != ''
)
UPDATE test
SET tags = CONCAT('[ ', STRING_AGG('"' + elem + '"', ' , '), ' ]')
FROM split_elements
WHERE test.id = split_elements.id;

注意:STRING_SPLIT仅在SQL Server 2016及以上版本支持,若使用更低版本需自定义字符串分割函数。

内容的提问来源于stack exchange,提问作者Ahmad Badpey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 16:22:54