MySQL keyword correlation ranking method detailed example analysis _mysql

Source: Internet
Author: User

Small projects sometimes need to use keyword search relevance sort, with Sphinx appear overkill, with the order of MySQL by against.
Method One:

Copy Code code as follows:

SELECT * from articles where (title-like '%keywords% ') or (content like '%helloworld% ') Order by ("case" title like '% keywords% ' THEN 2 else 0 end] + (case while content like '%helloworld% ' THEN 1 ELSE 0) ASC, Dateline DESC

Method Two:
For example, if the search keyword "IBM", "Server",
First, for the Search keyword processing, the code is as follows:
Copy Code code as follows:

$kw = Preg_replace ("/(\s+) | ( +) +/"," ", $kw);//instead of spaces, newline, tab, Chinese spaces
$kw = Preg_replace ("/(^\s*) | ( \s*$)/"," ", $kw);//Remove the trailing spaces
$kw = Preg_replace ("/(\s+)/", "", $kw);//replace multiple spaces with one space
$q = Explode (", $kw);//Enumeration keywords

There is also a need to add a code to remove the punctuation, but this code will have problems, do not know how to solve.

Then the code that generates the SQL statement

Copy Code code as follows:

$f = Array ("name", "description"); field of query Name= product name, description= product Description
$s = array (4,2); Weights, Name field matching points 4 points, description field matching product 2 points, and finally sorted by integral

Copy Code code as follows:

Create a query conditional 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 ";

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.