简体   繁体   English

如何从匹配项中排除特定单词?

[英]How do I exclude particular words from a match?

Suppose I have the following SQL query:假设我有以下 SQL 查询:

SELECT
  id, text
FROM
  comments
WHERE
  lower(text) LIKE '%hell%'
ORDER BY len(text) ASC

This matches any text that contains hell .这匹配包含hell任何文本。 However, I want to exclude a particular word from a match: "seashells".但是,我想从匹配中排除一个特定的词:“贝壳”。 How can I write an SQL query that matches everything that contains hell , but ignores seashells ?我如何编写一个 SQL 查询来匹配包含hell所有内容,但忽略seashells

Examples:例子:

  • He said hell o to the boy — matches.他对男孩说地狱——火柴。
  • Are there seashells on the beach?海滩上有贝壳吗? — no match. ——不匹配。
  • Uns hell ed seashells — matches.地狱贝壳——火柴。

You could try keeping your current logic but checking for %hell% after first removing seashells from the text:您可以尝试保留当前的逻辑,但在首先从文本中删除seashells后检查%hell%

SELECT id, text
FROM comments
WHERE LOWER(REPLACE(text, 'seashell', '')) LIKE '%hell%'
ORDER BY LEN(text);

Note that regex search would be a much better way to handle your requirement, but SQL Server does not have much built in regex support.请注意,正则表达式搜索将是处理您的需求的更好方法,但 SQL Server 没有太多内置的正则表达式支持。

You can try Not Like in Sql Query.您可以在 Sql Query 中尝试Not Like Here is something you can try.这是您可以尝试的方法。

SELECT
id, text
FROM
comments
WHERE
lower(text) LIKE '%hell%'
ORDER BY len(text) ASC

EXCEPT

SELECT
id, text
FROM
comments
WHERE
lower(text) LIKE '%seashells%'
OR
lower(text) LIKE '%other_word%'
ORDER BY len(text) ASC

To exclude some specific key word containing hell .排除某些包含地狱的特定关键字。 Note: NOT / LIKE IS CASE SENSITIVE.注意:NOT / LIKE 区分大小写。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM