SQL fuzzy Query sorting problem

Source: Internet
Author: User

Learn a little bit of programming every day PDF ebook, video tutorial free download:
Http://www.shitanlife.com/code Requirements Description
    • Query the data in the table with the specified keyword
    • Exact match in first place
    • Pre-match in second place
    • End match placed in third place
    • Middle match in fourth place
Build table
DROPTABLEIFEXISTS ' T_user '; create TABLE  ' T_user ' ( ' id ' varchar (20) not null,  Name ' varchar (20) DEFAULT null,  ' password ' varchar (20) default null,  PRIMARY key ( ' id ')) engine=innodb  DEFAULT Charset=utf8;               
Initial data
InsertInto T_userValues1,' Wang Feng ',' 888888 ');InsertInto T_uservalues (2, ' 王汪峰 ', insert into t_user values (3," Wang Feng Feng ",  888888 '); insert into t_user values (4, Ouyang Wang Feng ',  888888 '); insert into t_user values (5, ' Wang Wan PK ',  888888 ')                  
Direct like query
select * from t_user where name like ‘%汪峰%‘;
    • 1

The result is:

It can be found that "Wang Feng" is not arranged in front of "Wang Wangfeng"

Auxiliary sorting using case
SELECT *From T_user Fwhere F.nameLike'% Wang Feng% 'Orderby (casewhen f.name =  ' Wang Feng ' then 1 when f.name  Like  Wang Feng% ' then 2when f.name like  '% Wang Feng ' then 3when f.name like "% Wang Feng% ' then 4 Span class= "Hljs-keyword" >else 0end) limit 0,50;            

The query results are:

Equal to the addition of a virtual column to assist in sorting;
First match the full = =, and then follow the rules to match the next data, you can get the results we want.

Learn a little bit of programming every day PDF ebook, video tutorial free download:
Http://www.shitanlife.com/code

SQL fuzzy Query sorting problem

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.