SQL 查询中的 \% 和 \\ 是什么意思?

What does \% and \\ mean in a SQL query?

我知道 %_ 通配符的含义,但我被困在一个使用两个附加字符 \%\ 的问题中,我无法理解这些字符在 SQL 查询

中的实际含义
SELECT productID 
FROM productList 
WHERE productName LIKE 'ab\%cd%'

SELECT productID 
FROM productList 
WHERE productName LIKE 'ab\cd%'

这两个是相同的还是不同的??

由于 % 是一个特殊字符,您必须使用 \ 将其转义以匹配数据中的文字 % 符号。因此,'ab\%cd%' 匹配字母 a,然后是字母 b,然后是 % 符号、字母 c、字母 d,然后是任何其他文本(因为最后一个 % 是通配符)。

同样,由于 \ 是用于创建转义序列的特殊字符,您必须将其转义以匹配模式中的文字 \,因此要匹配单个 \ 你必须将它编码为 \.

我相信通过示例了解差异的最佳方式。

为了更好地理解它,在 SQL 中使用 LIKE 运算符时,您需要了解 3 件事:

  • \ 用于转义特殊字符以将它们用作普通字符
  • %用于匹配任意数量的字符(包括0)
  • 特殊字符是 \% 所以如果你想按字面意思包含它们你需要转义它们,所以要在文本列中检查它们你分别需要使用 \\%.

下面是 table 的单词和 true/false 结果 LIKE 与两种模式的比较:

   word   | ab\%cd% | ab\cd%
----------+---------+---------
 ab\      | f       | f        -- this would match second pattern but there is no "cd" at the end
 ab\cd    | f       | t        -- \ is escaped "\", and % matches none characters
 ab\cdxzy | f       | t        -- \ is escaped "\", and % matches character sequence "xzy"
 abcd     | f       | f        -- every string requires either "%" or "\" character after "ab"
 ab%cd    | t       | f        -- \% is escaped "%", and % matches none characters
 ab%cdxzy | t       | f        -- \% is escaped "%", and % matches character sequence "xzy"
 ab\%cd   | f       | f        -- there is no pattern which matches both chars "\%" in sequence
 ab%\cd   | f       | f        -- same as above, but characters are "%\" in sequence

The \% and \_ sequences are used to search for literal instances of % and _ in pattern-matching contexts where they would otherwise be interpreted as wildcard characters.

对于 \,它搜索单个反斜杠 \

参考:MySQL 8.0 Reference Manual, 9.1.1 String Literals, Table 9.1 Special Character Escape Sequences