在 `LIKE` 中一起使用 `_%` 不会返回准确的数据

Using `_%` together in `LIKE` is not returning exact data

我猜这可能很容易回答类型问题,但我是第一次面对它,所以任何帮助将不胜感激。

我的查询:

SELECT remarks FROM enroll WHERE remarks LIKE 'REC_%'

输出:

remarks
REC_59161
Reclassify Hedge

预期输出仅为 REC_59161。是的 _ 用于匹配任何单个字符,但我只是在寻找实现我预期的输出。

_ 是一个 wildcard Character。所以你必须使用 [].

来逃避它

查询

select remarks
from enroll
where remarks like 'REC[_]%';

下划线_字符实际上是带有LIKE运算符的特殊字符,%[]^:[=20也是如此=]

https://docs.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql

在那篇文章中,您会看到下划线 _ 匹配任何单个字符。

使用ESCAPE 关键字定义转义字符,以允许您转义模式匹配字符。我们可以使用!作为转义符,所以:

WHERE remarks LIKE 'REC!_%' ESCAPE '!'

_ 是通配符,试试这个:

declare @enroll table (remarks varchar(50));
insert into @enroll values ('REC_59161') , ('Reclassify Hedge');
SELECT remarks FROM @enroll WHERE remarks LIKE 'REC[_]%';

Demo

有两个问题:

  1. 该列似乎不区分大小写,详情请参阅Is the LIKE operator case-sensitive with MS SQL server?。这就是为什么 Reclassify Hedge 中的 Rec 适合 Like
  2. 中的 REC
  3. _(以及%)是一个外卡,你应该转义_ 在模式中

查询:

  SELECT remarks 
    FROM enroll 
   WHERE remarks LIKE 'REC*_%' ESCAPE '*' /* SQL 92 standard */

http://www.contrib.andrew.cmu.edu/~shadow/sql/sql1992.txt

uses the triadic operator LIKE (or the inverse, NOT LIKE), operating on three character strings and returning a Boolean. LIKE determines whether or not a character string "matches" a given "pattern" (also a character string). The characters '%' (percent) and '_' (underscore) have special meaning when they occur in the pattern. The optional third argument is a character string containing exactly one character, known as the "escape character", for use when a percent or underscore is required in the pattern without its special meaning.