MySQL 为什么“_”(下划线)匹配“-”(连字符)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8236818/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 21:47:51  来源:igfitidea点击:

Why does "_" (underscore) match "-" (hyphen)?

mysqlwildcard

提问by E.G.

I have to look for a PDF manual using this query:

我必须使用此查询查找 PDF 手册:

root@localhost:test> select * from a where name like '%taz_manual%.pdf%';
+--------------------+------------------+-------------+
| name               | description      |        size | 
+--------------------+------------------+-------------+
| taz-manual-1.1.pdf | Manual v1.0 TA-Z |    31351902 |
| taz-manual-0.2.pdf | Manual v1.0 T1-A |     3578278 |
| taz_manual-2.0.pdf | Manual v2.0 GA-X |   542578278 |
etc........
+--------------------+------------------+-------------+
132 row in set (0.00 sec)

Why am I seeing the the one with dashes when I specify the name to be taz_manual%.pdf?

当我指定名称时,为什么会看到带破折号的那个taz_manual%.pdf

回答by Book Of Zeus

Because the underscore _is a wildcard like the percent %, except that it only looks for one character.

因为下划线_是一个和百分比一样的通配符%,只不过它只查找一个字符。

SQL pattern matching enables you to use "_" to match any single character and "%" to match an arbitrary number of characters (including zero characters).

SQL 模式匹配使您可以使用“_”来匹配任何单个字符,使用“%”来匹配任意数量的字符(包括零个字符)。

(From section 3.3.4.7. Pattern Matchingin the MySQL documentation.)

(来自MySQL 文档中的3.3.4.7. 模式匹配部分。)

If you want to use the underscore in likeas a literal, you have to escape it:

如果要将下划线like用作文字,则必须对其进行转义:

select * from a where name like '%taz\_manual%.pdf%';

回答by NBhat

I had a similar issue with space and hyphens while matching strings with exact match:

在将字符串与完全匹配匹配时,我遇到了类似的空格和连字符问题:

SELECT id FROM location WHERE name = 'IND - HQ';

The above query didn't return any records in MySQL. I had to escape the spaces and hyphens and use LIKEinstead of exact match with equals (=) as follows:

上述查询在 MySQL 中没有返回任何记录。我不得不转义空格和连字符,并使用LIKE等于 (=) 而不是完全匹配,如下所示:

SELECT id FROM location WHERE name LIKE 'IND_\-_HQ';