[英]SQL - NOT LIKE and LIKE with only characters
I am learning SQL(without concrete implementation). 我正在学习SQL(没有具体实现)。
I need to validate that some value contains only characters using LIKE or NOT LIKE 我需要验证某些值仅包含使用LIKE或NOT LIKE的字符
1 .Incorrect example is: 1。不正确的示例是:
SELECT * FROM table WHERE name LIKE '%[a-zA-Z]'
because ' 123A123 ' would be true 因为' 123A123 '为真
2 . 2 。 I read up that It would work
我读到它会工作
SELECT * FROM table WHERE name NOT LIKE '%[^a-zA-Z]%'
These queries look equal to me(It's like to compare 5 and --5) 这些查询看起来和我一样(就像比较5和--5)
Could you explain please what is the difference between? 您能解释一下有什么区别吗?
This expression: 该表达式:
WHERE name NOT LIKE '%[^a-zA-Z]%'
matches all names that have a character that is not a letter, such as .
匹配所有具有非字母字符的名称,例如
.
or ;
或
;
or whatever. 管他呢。
This expression: 该表达式:
name LIKE '%[a-zA-Z]'
matches all names that contain at least one letter. 匹配包含至少一个字母的所有名称。
So, 'ABC.DEF'
will match both patterns -- it matches the first because it has .
因此,
'ABC.DEF'
将匹配这两种模式-因为具有,所以它匹配第一种.
and the second because it has a letter. 第二个是因为它有一个字母。
However, 'ABC'
does not match the first pattern because it only consists of letters. 但是,
'ABC'
与第一个模式不匹配,因为它仅由字母组成。 It does match the second one. 它确实与第二个匹配。
Ok, let's dissect this: 好的,让我们对此进行剖析:
NOT LIKE '%[^a-zA-Z]%'
The regexp here is "does not contain any letters". 这里的正则表达式是“不包含任何字母”。 If we negate using
NOT LIKE
, it'll mean "contains only letters". 如果我们使用
NOT LIKE
否定,则表示“仅包含字母”。
Now: 现在:
name LIKE '%[A-Za-z]%'
Regexp here means "contains at least one letter". 正则表达式在这里意味着“包含至少一个字母”。 So
LIKE
on that will mean the same thing. 因此,
LIKE
那样表示相同的意思。
So: 所以:
SELECT * FROM (VALUES ('A123'), ('123'), ('AAA'), (',')) x(name)
WHERE name LIKE'%[A-Za-z]%'
This will return both A123
(there's an A) and AAA
, but neither 123
(only digits) nor ,
(still not a letter) will get returned. 这将同时返回
A123
(有一个A)和AAA
,但是123
(仅数字)或,
(仍不是字母)都不会返回。
SELECT * FROM (VALUES ('A123'), ('123'), ('AAA'), (',')) x(name)
WHERE name NOT LIKE '%[^A-Za-z]%'
This one will only return AAA
because it's the only one containing letters only. 这是一个仅包含字母的字母,只会返回
AAA
。 AAA
is the only record that regexp will not match, and since we're negating with NOT LIKE
, it means only this one meets the WHERE
condition. AAA
是唯一不符合regexp的记录,并且由于我们与NOT LIKE
否定,因此这意味着只有该记录符合WHERE
条件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.