使用 RLIKE 排除某些字符串同时包含其他字符串

Exclude certain strings while including others using RLIKE

我正在研究使用 RLIKE 函数在文本块中查找特定单词的 Snowflake 查询。 这是我的查询的简化版本:

SELECT id FROM table WHERE RLIKE (text,'.* red .*|.* green .*|.* blue .*','i')

我正在查询的 table 的一些示例:

第 1 行:id = 1,文本 = 'the table is red and nice'

第 2 行:id = 2,text = '花园里有一朵红玫瑰'

第 3 行:id = 3,文本 = 'I see a red rose in the green garden'

此时,查询将 return 来自 table 的所有 3 行。 我要做的是从结果中排除某个单词组合。在此示例中,我想从结果中排除 'red rose',但前提是文本中的 RLIKE 列表中没有其他词。

所以在我的结果中,应该包含 ID 1(必须包含 'red' 本身),应该排除 ID 2('red rose' 组合并且文本中没有其他颜色)和ID 3 应该包括在内(即使它有 'red rose',它也有 'green',所以应该包括在内)。

有什么办法吗?提前感谢您的帮助

编辑:澄清一下,我还想在我的结果中看到类似 'the red rose in the red garden' 的内容,因为 'red' 曾经在那里,而不是 'rose'

嗯。 . .以下可能足以满足您的需求,并且不使用正则表达式:

SELECT id
FROM table
WHERE text like '% green %' or
      text like '% blue %' or
      (text like '% red %' and text not like '% red rose %');

这适用于您的示例数据。但它不会return“红花园里的红玫瑰”。我不确定你是否想要那个。

如果您希望该行也出现,那么一种方法是:

SELECT id
FROM table
WHERE text like '% green %' or
      text like '% blue %' or
      replace(text, 'red rose', '') like '% red %' ;

您可以使用具有相同逻辑的 rlike()

WHERE rlike(replace(text, 'red rose', ''), ' red | green | blue ')