我知道%
和_
通配符的含义,但我被困在一个问题,使用了两个额外的字符\%
和\\
,我无法理解这些字符在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)\
和%
所以如果你想要逐字地包含它们你需要逃避它们,所以要在文本列中检查它们你分别需要使用\\
和\%
。下面是一个表格,其中包含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
\%
和\_
序列用于在模式匹配上下文中搜索%
和_
的文字实例,否则它们将被解释为通配符。
对于qazxsw poi,它搜索单个反斜杠qazxsw poi。
参考:\\