mysql fuzzy query, the user wildcard '_' and '%' Process

        When the project using the mysql field and fuzzy search, if the system did not do a character for field restrictions, user input will often underscore '_' percent '%' wildcard searches such, so tend to perform result set retrieved error, down-line '_' matches any single character, percent '%' matches any arbitrary character.

        In order to facilitate understanding. for example: when using fuzzy matching like, as conventional wording: field like CONCAT ( '%', variable, '%')     

                                                                Then the result is: field like '% keyword%', then search out the results are correct.

        Then the question is, a single user input "_", the statement is executed at this time field like '% _%', the matching results at this time is when all the data of an entire table.

        Or this:

                        field like '%%%', with predictable results

solution

         First, like the use of alternative INSTR

                     INSTR does not recognize wildcards, only the second string parameter is determined whether there is the first string. Make sure that this theory is evidence-based, Shangguan net.


INSTR usage (official website screenshot)

        This only shows that the index position of the first letter of the second parameter will function in the first parameter first appears. The document read by the majority of users were found where the function is used to achieve the effect of fuzzy words in the query.

use:

        select * form users where INSTR (users_name, 'user input') is equivalent to select * from users where users_name like CONCAT ( '%', 'user input', '%'), in simple terms, is equivalent to the java INSTR string.contains ( "") method

 


    Second, use the escape character '\'

               '\%' Will be escaped as '%' empathy '\ _' will be escaped as '_', the filter value entered by the user in your programming language, encountered a wildcard to fill in front of the '\'

    Third, the use ESCAPE escape

                Use (the use of unfamiliar, let us give you an example)


Examples

                This is the meaning of the wording of the '/' character behind the character is treated as an ordinary character, instead of a wildcard, this approach has a back problem, and finally a '%' should be treated as a wild card is correct.

Guess you like

Origin www.cnblogs.com/lzwnodes/p/11653454.html