如何在 MySQL 中查询包含给定文本的字段?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8070314/
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
How do I query for fields containing a given text in MySQL?
提问by TIMEX
SELECT stuff REGEXP 'itunes' as is_itunes;
In this MySQL query, if "stuff" has the word "itunes" in it, it will mark it as itunes.
在这个 MySQL 查询中,如果“stuff”中有“itunes”这个词,它会将其标记为 itunes。
However, I want to say "begin with". How can I check for "begin with" instead of anywhere in the text?
但是,我想说“开始于”。如何检查“开始于”而不是文本中的任何地方?
回答by Marc B
SELECT ... WHERE stuff LIKE 'itunes%';
Here %
serves as a wildcard character, so this would match rows with the stuff
field equal to any of itunes
, itunesfoo
, itunes1
, ...
这里%
用作通配符,因此这将匹配stuff
字段等于itunes
, itunesfoo
, itunes1
, ...
More info: SQL LIKE Operatorat W3Schools.
更多信息:SQL LIKE操作员在W3Schools的。
回答by Kaivosukeltaja
Add the caret symbol, it represents the beginning of the string:
添加脱字符号,它代表字符串的开头:
SELECT stuff REGEXP '^itunes' as is_itunes;
However, LIKE 'itunes%'
as suggested by Marc should be a lot faster, especially if your indexes are set up correctly.
但是,LIKE 'itunes%'
正如 Marc 所建议的那样,速度应该快得多,尤其是在您的索引设置正确的情况下。
回答by O_Z
For an indexed field it is much better to do:
对于索引字段,最好这样做:
select ... where stuff >='itunes' AND stuff < 'itunet'
select ... where stuff >='itunes' AND stuff < 'itunet'
This will not create a full table scan, and use the index.
这不会创建全表扫描,并使用索引。
回答by Meelah
SELECT ... WHERE LEFT(stuff, 6) = 'itunes';
回答by Elaine
SELECT ... WHERE stuff REGEXP '[[:<:]]itunes';