SQL 使用 Oracle 点赞和通配符 SQL 开发人员

SQL Like and Wildcard with Oracle SQL Developer

我在后端 Oracle 数据库上使用 SQL Developer。我有买家姓名为 Pete Hansen 的记录。

为什么我尝试

select * from data1 where buyer = 'Pete Hansen';

我得到了结果,没问题。但是,当我使用以下内容时,我没有得到任何结果:

select * from data1 where buyer  like 'Pete Hansen';

此外,当我尝试以下操作时,我没有得到任何结果

select * from data1 where buyer like 'Pete Hans_n';

但以下效果很好:

select * from data1 where buyer like 'Pete Hans_n%';

你能帮我理解一下吗?提前致谢。

我怀疑这可能与尾随空格有关,like 运算符不宽容但 = 是。要对此进行测试,请尝试

select * from data1 where trim(buyer) like 'Pete Hansen';

您的 buyer 列似乎定义为 char;你可以看到重现的问题 in this db<>fiddle, but not when the column is varchar2.

documentation for character comparison 解释了空白填充或非填充比较语义之间的区别。当您将它们与 = 进行比较时,因为列和字符串文字都是 `char,所以使用了空格填充的语义:

With blank-padded semantics, if the two values have different lengths, then Oracle first adds blanks to the end of the shorter one so their lengths are equal. ... If two values have no differing characters, then they are considered equal. This rule means that two values are equal if they differ only in the number of trailing blanks. Oracle uses blank-padded comparison semantics only when both values in the comparison are either expressions of data type CHAR, NCHAR, text literals, or values returned by the USER function.

当列为 `varchar2 时,将使用非填充语义:

With nonpadded semantics, ... If two values of equal length have no differing characters, then the values are considered equal. Oracle uses nonpadded comparison semantics whenever one or both values in the comparison have the data type VARCHAR2 or NVARCHAR2.

LIKE 的工作方式不同。只有带有 % 的最终模式匹配,因为这允许 char 值中的尾随空格,而其他两个模式则不允许。对于 varchar2 版本,其他两个模式也没有匹配的尾随空格。

很少需要或想要用户 char 列; varchar2 比较常见。 Tom Kyte opined on this很多年前。