Four USES of fuzzy queries in mysql

  • 2020-06-12 10:47:54
  • OfStack

Here are four USES of fuzzy queries in mysql:

1, % : Represents any 0 or more characters. Characters of any type and length can be matched. In some cases, in Chinese, use two percent signs (%%).
SELECT * FROM [user] WHERE u_name LIKE '%3%'
u_name will be found as "Zhang 3", "Zhang Cat 3", "3-legged cat", "Tang 3 Hide" and so on.
Also, if you need to find a record in u_name that has both a "3" and a "cat", use the and condition
SELECT * FROM [user] WHERE u_name LIKE '% 26en 'u_name LIKE '% cats %'
SELECT * FROM [user] WHERE u_name LIKE '%3% cat %'

Although can search out "3 feet cat", but cannot search out to meet the criteria "zhang Cat 3".

2, _ : Represents any single character. Matches a single arbitrary character, which is commonly used to limit the character length statement of an expression:
SELECT * FROM [user] WHERE u_name LIKE '_3_'
Find only "Tang 3 Zang", so u_name is 3 characters and the middle one is "3";

SELECT * FROM [user] WHERE u_name LIKE '3__'; Find only the "3-legged cat" so that name is 3 words and the first word is 3;

3, [] : represents one of the characters listed in parentheses (similar to a regular expression). Specifies a character, string, or range to match any one of them.
For example, SELECT * FROM [user] WHERE u_name LIKE '[Wang Li]3' will find "Zhang 3", "Li 3", and "Wang 3" (not "Wang Li 3");
"0-4", "ES75en-ES76en" if there is a series of characters (01234, abcde, etc.) in []
SELECT * FROM [user] WHERE u_name LIKE 'old [1-9]' will find' old 1 ', 'old 2',... "Old 9";

4, [^] : Represents a single character that is not listed in parentheses. The value is the same as [], but it requires the matched object to be any character other than the specified character.
For example, SELECT * FROM [user] WHERE '[^ wang Li]3' will find "zhao 3", "Sun 3" and so on.
SELECT * FROM [user] WHERE u_name LIKE 'old [^1-4]'; Exclude "old 1" to "old 4" and look for "old 5", "old 6",...

5, when the query contains wildcards
Because of the wildcard, the query for the special characters "%", "_" and "[" cannot be implemented normally, but the query can be performed normally by enclosing the special characters" [] ". Accordingly, we write the following function:
function sqlencode(str) str=replace(str,"';","';';")
str=replace(str,"[","[]") '; str=replace(str,"_","[_]") str=replace(str,"%","[%]") sqlencode=str end function

Related articles: