Mysql keyword relevance sorting method detailed example analysis

Source: Internet
Author: User

Small projects sometimes need to use keywords to search for relevance sorting. If sphinx appears to be a zombie, use order by of mysql to deal with it.
Method 1:
Copy codeThe Code is as follows:
Select * from articles where (title LIKE '% keywords %') or (content LIKE '% helloworld % ') order by (case when title LIKE '% keywords %' THEN 2 ELSE 0 END) + (case when content LIKE '% helloworld %' THEN 1 ELSE 0 END) ASC, dateline DESC

Method 2:
For example, if you search for the keyword "IBM" or "server ",
First, the code for processing the search keyword is as follows:
Copy codeThe Code is as follows:
$ Kw = preg_replace ("/(\ s +) | (+) +/", "", $ kw); // Replace space, line feed, tab, Chinese Space
$ Kw = preg_replace ("/(^ \ s *) | (\ s * $)/", "", $ kw); // remove spaces at the beginning and end
$ Kw = preg_replace ("/(\ s +)/", "", $ kw); // replace multiple spaces with one space
$ Q = explode ('', $ kw); // enumeration keyword

You also need to add a code to remove punctuation marks, but this Code may have problems and I don't know how to solve them.

Then the code for generating the SQL statement
Copy codeThe Code is as follows:
$ F = array ("name", "description"); // The queried field name = product name, description = product description
$ S = array (); // weight, the name field matches points for 4 points, the description field matches product 2 points, and finally sorts by points

Copy codeThe Code is as follows:
// Create a query Condition Statement
For ($ I = 0; $ I <count ($ q); $ I ++ ){
For ($ j = 0; $ j <count ($ f); $ j ++ ){
$ Clause [$ c] = "(". $ f [$ j]. "LIKE '%". $ q [$ I]. "%')";
$ Score [$ c] = "IF (LOCATE ('". $ q [$ I]. ','. $ f [$ j]. "),". $ s [$ j]. ", 0)";
$ C ++;
}
}
$ SQL = "SELECT id, name, description,
(". Implode (" + ", $ score).") AS score
FROM product
WHERE (". implode (" OR ", $ clause ).")
Order by score DESC ";

Related Article

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.