sql like 语句获得了意想不到的结果
sql like statement picking up unexpected results
我有一个简单的table如下
id, target
-----------
1, test_1
2, test_2
3, test_3
4, testable
我有一个简单的查询:
select * from my_table where target like 'test_%'
我期待的是前 3 条记录,但我得到了所有 4 条记录
参见 SQLFiddle example here
下划线是模式匹配字符。试试这个:
select * from my_table where target like 'test[_]%'
下划线是表示 "match any character single character" 的通配符,就像 % 是表示 "match any 0 or more characters" 的通配符一样。如果您熟悉正则表达式,下划线字符相当于那里的点。您需要正确地转义下划线以从字面上匹配该字符。
_ 也是一个通配符。您可以像这样转义它:
... like 'test\_%' escape '\'
您使用的下划线字符 _ 是单个字符的通配符,因此它 returns 4 行。尝试使用 [_] 而不是 _。
为了说明..
CREATE TABLE #tmp (val varchar(10))
INSERT INTO #tmp (val)
VALUES ('test_1'), ('test_2'), ('test_3'), ('testing')
-- This returns all four
SELECT * FROM #tmp WHERE val LIKE 'test_%'
-- This returns the three test_ rows
SELECT * FROM #tmp WHERE val LIKE 'test[_]%'
我有一个简单的table如下
id, target
-----------
1, test_1
2, test_2
3, test_3
4, testable
我有一个简单的查询:
select * from my_table where target like 'test_%'
我期待的是前 3 条记录,但我得到了所有 4 条记录
参见 SQLFiddle example here
下划线是模式匹配字符。试试这个:
select * from my_table where target like 'test[_]%'
下划线是表示 "match any character single character" 的通配符,就像 % 是表示 "match any 0 or more characters" 的通配符一样。如果您熟悉正则表达式,下划线字符相当于那里的点。您需要正确地转义下划线以从字面上匹配该字符。
_ 也是一个通配符。您可以像这样转义它:
... like 'test\_%' escape '\'
您使用的下划线字符 _ 是单个字符的通配符,因此它 returns 4 行。尝试使用 [_] 而不是 _。
为了说明..
CREATE TABLE #tmp (val varchar(10))
INSERT INTO #tmp (val)
VALUES ('test_1'), ('test_2'), ('test_3'), ('testing')
-- This returns all four
SELECT * FROM #tmp WHERE val LIKE 'test_%'
-- This returns the three test_ rows
SELECT * FROM #tmp WHERE val LIKE 'test[_]%'