MySQL Fuzzy Queries: Wildcards Explained
The main method of conducting MySQL fuzzy searches is through the use of wildcards, with common wildcards including:
- %: represents any character appearing 0 or more times.
- “_ : represents any single character”
- [charlist]: Represents a character in the specified set of characters.
- [^charlist]: denotes a character that is not in the specified character set
Common usage of fuzzy queries includes:
- Search for records that begin with a specific character or string:
SELECT * FROM table_name WHERE column_name LIKE 'prefix%';
- Search for records that end with a specific character or string.
SELECT * FROM table_name WHERE column_name LIKE '%suffix';
- Search for records containing specific characters or strings.
SELECT * FROM table_name WHERE column_name LIKE '%keyword%';
- Querying characters or strings of specified length using wildcard _.
SELECT * FROM table_name WHERE column_name LIKE '______'; -- 查询长度为6的字符串
- Search for records that contain specified character sets using wildcards [charlist] and [^charlist].
SELECT * FROM table_name WHERE column_name LIKE '[abc]%'; -- 查询以a、b或c开头的记录
SELECT * FROM table_name WHERE column_name LIKE '[^abc]%'; -- 查询不以a、b或c开头的记录
It is important to note that when using fuzzy queries, make sure the field type of the table is a string type, or else errors may occur.