[英]selecting values that do not have '_' with mysql
I was looking for a way to exclude values with a '_' in the results set from a mysql database. 我一直在寻找一种方法来从mysql数据库的结果集中排除带有'_'的值。
Why would the following sql statement return no results? 为什么以下sql语句不返回任何结果?
select questionKey
from labels
where set_id = 674
and questionKey like 'Class%'
and questionKey not like '%_%' ;
which was the first sql I tried where as 这是我尝试在哪里的第一个sql
select questionKey
from labels
where set_id = 674
and questionKey like 'Class%'
and locate('_',questionKey) = 0 ;
returns 退货
questionKey
ClassA
ClassB
ClassC
ClassD
ClassE
ClassF
ClassG
ClassNPS
ClassDis
which is the result I wanted. 这是我想要的结果。 Both SQL statements appear to me to be logically equivalent though they are not.
在我看来,两个SQL语句在逻辑上都是等效的,尽管它们在逻辑上并不相同。
In the LIKE
context _
takes on special meaning and represents any single character . 在
LIKE
上下文中, _
具有特殊含义,代表任何单个字符 。 It's the only one other than %
that means something here. 这是
%
以外唯一的一个在这里表示某种意义的东西。
Your LOCATE()
version is probably the best here, though it's worth noting that doing table scans like this can get cripplingly slow on large amounts of data. 您的
LOCATE()
版本可能是这里最好的版本,但是值得注意的是,执行这样的表扫描可能会严重破坏大量数据。 If underscore represents something important you might want to have a flag field you can set and index. 如果下划线表示重要的内容,则可能需要一个可以设置和索引的标志字段。
You could also use a regular expression to try and match records with a single condition: 您还可以使用正则表达式尝试匹配具有单个条件的记录:
REGEXP '^Class[^_]+'
As tadman and PM77 already pointed out, it's a special character. 正如塔德曼和PM77所指出的那样,这是一个特殊的角色。 If you want to use the first query, try to escape it like this (note the backslash):
如果要使用第一个查询,请尝试像这样对它进行转义(注意反斜杠):
select questionKey
from labels
where set_id = 674
and questionKey like 'Class%'
and questionKey not like '%\_%' ;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.