【问题标题】:Exclude returned data when specific words or phrases exist存在特定单词或短语时排除返回的数据
【发布时间】:2021-12-31 18:29:05
【问题描述】:

下面是一个正在返回的数据示例。

ID CensoredWord DescriptionSnippet
1 anus anus
2 anus manuscript submitted
3 anus tetanus vaccination
4 anus oceanus proposal
5 rere prerequisite includes

描述片段在另一个词或短语中包含被删减的词,并且可以是多个句子。

当单词是 anus 并且 sn-p 包含单词 tetanus 或practice 或 oceanus 并且同样具有单词 rere 并且 sn-p 包含先决条件时,我想排除返回数据。

我在 WHERE 周围尝试了各种方法

CensoredWord = 'anus' 和 DescriptionSnippit NOT LIKE '%tetanus%'

OR CensoredWord = 'anus' 和 DescriptionSnippit NOT LIKE '%manuscript%'

OR CensoredWord = 'anus' 和 DescriptionSnippit NOT LIKE '%oceanus%'

OR CensoredWord = 'rere' 和 DescriptionSnippit NOT LIKE '%prerequisite%'

但我做得不够好。这应该是什么样子?

【问题讨论】:

  • 我轻笑了一声。
  • 您似乎想要更多这样的东西。 WHERE NOT (word = 'anus' AND descr LIKE '%xxx%' OR word = 'rera' AND descr LIKE '%yyy%' OR ...) ...如果猜测正确,我会添加这个作为答案。看来您可能问错了问题。我只是不确定。
  • ID=1的DescriptionSnippet不应该是tetanus吗?

标签: sql where-clause


【解决方案1】:

假设您只是不希望句子包含被删减的词,而忽略包含它的词。

那么这将适用于大多数 SQL 方言。
但这并不完美。
F.e.它不会找到anus!

select *
from test
where concat(' ',description_snippet,' ') not like 
concat('% ',censored_word,' %') 

一些 RDBMS 具有接受正则表达式的函数。这提供了更大的灵活性。
F.e.词边界的使用。

这是一个适用于 Postgresql 的示例

测试

create table test (
 ID serial primary key, 
 censored_word varchar(30),
 description_snippet varchar(30)
);

insert into test (id, censored_word, description_snippet) values
  (1, 'anus', 'anus')
, (2, 'anus', 'manuscript submitted')
, (3, 'anus', 'tetanus vaccination') 
, (4, 'anus', 'oceanus proposal')
, (5, 'rere', 'prerequisite includes')
, (6, 'rere', 'no rere without anus')
select *
from test
where description_snippet !~ concat('\m(', censored_word, ')\M') 
id censored_word description_snippet
2 anus manuscript submitted
3 anus tetanus vaccination
4 anus oceanus proposal
5 rere prerequisite includes

db小提琴here

【讨论】:

    【解决方案2】:

    您可以使用正则表达式搜索在 censored_word 之前或之后至少有一个字母的 description_sn-ps。

    select * from test where lower(description_snippet) regexp lower(concat("[[:alpha:]]",censored_word,"|",censored_word,"[[:alpha:]]"));
    

    或者像这样使用

    select * from test where lower(description_snippet) like (concat('%',lower(censored_word))) or lower(description_snippet) like(concat(lower(censored_word),"%"));
    

    http://sqlfiddle.com/#!9/a471f3/7

    【讨论】:

    • 不知道OP具体的RDBMS,不是都支持使用regex。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-12
    • 1970-01-01
    • 2020-08-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多