SQL如何使用正则表达式根据其他列的值新增对应取值的新列
实现方案
核心是用正则匹配type字段中是否存在独立的harm片段,规则为:harm要么是字段的完整值,要么是下划线分隔的独立片段,避免匹配到sharm这类前面带其他字符的内容。
正则匹配规则
使用正则表达式:(^|_)harm($|_)
^|_匹配字符串开头或者下划线,确保harm前面没有其他普通字符$|_匹配字符串结尾或者下划线,确保harm后面没有其他普通字符
不同SQL方言的实现示例
PostgreSQL
SELECT value, type, CASE WHEN type ~ '(^|_)harm($|_)' THEN 'harm' ELSE 'not_harm' END AS is_harm FROM "my_data";
MySQL
SELECT value, type, CASE WHEN type REGEXP '(^|_)harm($|_)' THEN 'harm' ELSE 'not_harm' END AS is_harm FROM `my_data`;
SQL Server
SELECT value, type, -- 高版本SQL Server也可直接用正则:CASE WHEN type REGEXP '(^|_)harm($|_)' THEN 'harm' ELSE 'not_harm' END AS is_harm CASE WHEN type LIKE 'harm' OR type LIKE 'harm[_]%' OR type LIKE '%[_]harm' OR type LIKE '%[_]harm[_]%' THEN 'harm' ELSE 'not_harm' END AS is_harm FROM my_data;
上述实现完全匹配你的示例要求:
- 匹配成功的场景:
harm、harm_2、xxx_harm、xxx_harm_xxx - 匹配失败的场景:
sharm、sharm_9、harmxxx
内容的提问来源于stack exchange,提问作者french_fries
相关产品推荐
相关产品推荐

