【问题标题】:what is difference among '\', '\\', '\\\' when LIKE matching for float number?LIKE匹配浮点数时,'\','\\','\\\'有什么区别?
【发布时间】:2021-04-14 09:05:47
【问题描述】:

使用原始查询,我尝试在下面的列中匹配测试表中名称为“desc”的关键字。

desc 
The progress is above 93% or not
The progress is above 93.1% or not
The progress is above 93.15% or not

使用关键字 '93%' 仅匹配 93% 不包括 93.1% 或 93.15% 的完全匹配

SELECT desc FROM test WHERE Replace(desc, ' ', '') LIKE '%93%%';

我们可以看到所有三个结果。

SELECT desc FROM test WHERE Replace(desc, ' ', '') LIKE '%93\%%';

我们可以看到所有三个结果。

SELECT desc FROM test WHERE Replace(desc, ' ', '') LIKE '%93\\%%';

这一次,我只能得到 1 个完全匹配的结果。

SELECT desc FROM test WHERE Replace(desc, ' ', '') LIKE '%93\\\%%';

这个也和'\\'一样

请解释一下区别。

【问题讨论】:

  • 数字不是文字。 LIKE 不适用于数字。您发布的是 text,而不是浮点数。在一些国家/地区,93.5 可以按百分比处理。
  • 您正在尝试匹配复杂的文本模式。 LIKE 做不到。为此,您需要一个正则表达式。 SQL 语言不支持正则表达式。像 PostgreSQL 这样的一些数据库提供了正则表达式方法,但是这些方法不能利用索引。如果您使用正则表达式仅查找 `93%`,则必须扫描表中的所有行。这很慢。
  • 你想做什么?您想解决的真正问题是什么?如果您想识别特定的日志条目,请使用将您要过滤的数据存储在单独的索引字段中的表模式,例如Progress 字段。或者使用单独的表来跟踪您想要的信息,例如带有progress 字段的JobsJobHistory 表。对于适量的数据,您可以将数据记录为 JSON 或 XML,并带有不同的 progress 字段,您可以使用 JSON 函数提取这些字段。您可能能够创建并索引一个公开progress 值的计算列
  • @PanagiotisKanavos:运算符 similar to 是 SQL 标准的一部分,并且确实支持正则表达式(尽管不完全符合 POSIX 正则表达式)
  • @a_horse_with_no_name 然而,大多数数据库甚至在 20 年后都使用REGEXP_LIKE。看起来只有 PostgreSQL 和 Firebird 支持 SIMILAR TO 甚至 it looks to be a compromise doomed to failure。这是……具有大多数 SQL 功能的共同主题。可以为 SQL 创建一个类似皇冠的肥皂剧。我怀疑 Codd、Date 和 Darwen would even say compromise doomed to fail 是指导原则

标签: sql postgresql sql-like backslash


【解决方案1】:

我唯一的解释是,您要么使用的是古老的 PostgreSQL 版本,要么将 standard_conforming_strings 设置为 off

然后您应该会收到警告,除非您已将 escape_string_warning 设置为 off

test=> SET standard_conforming_strings = off;
SET
test=> SELECT 'above 93.15% or not' LIKE '%93%%';
 ?column? 
══════════
 t
(1 row)

test=> SELECT 'above 93.15% or not' LIKE '%93\%%';
WARNING:  nonstandard use of escape in a string literal
LINE 1: SELECT 'above 93.15% or not' LIKE '%93\%%';
                                          ^
HINT:  Use the escape string syntax for escapes, e.g., E'\r\n'.
 ?column? 
══════════
 t
(1 row)

test=> SELECT 'above 93.15% or not' LIKE '%93\\%%';
WARNING:  nonstandard use of \\ in a string literal
LINE 1: SELECT 'above 93.15% or not' LIKE '%93\\%%';
                                          ^
HINT:  Use the escape string syntax for backslashes, e.g., E'\\'.
 ?column? 
══════════
 f
(1 row)

test=> SELECT 'above 93.15% or not' LIKE '%93\\\%%';
WARNING:  nonstandard use of \\ in a string literal
LINE 1: SELECT 'above 93.15% or not' LIKE '%93\\\%%';
                                          ^
HINT:  Use the escape string syntax for backslashes, e.g., E'\\'.
 ?column? 
══════════
 f
(1 row)

【讨论】:

    猜你喜欢
    • 2011-03-20
    • 2021-09-26
    • 2011-01-24
    • 2014-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-23
    • 1970-01-01
    相关资源
    最近更新 更多