简体   繁体   中英

ZEND and MySQL - How to search and ORDER BY (sort) relevance?

I'm going to write a simple search on products table, and when user is searching for something I use product_name LIKE %search_term% to search the product table. But I need to sort them by relevance.

I'm using ZEND freamwork and my database is MySQL

Here someone asked about how to ORDER BY relevance in MySQL and someone suggested a good query for that, what you need to do is:

 SELECT  product_name
  FROM products
 WHERE product_name like '%search_term%'
 GROUP BY name
 ORDER BY CASE WHEN product_name like 'search_term %' THEN 0
               WHEN product_name like 'search_term%' THEN 1
               WHEN product_name like '% search_term%' THEN 2
               ELSE 3
          END, product_name

You will get the search_term from user, and have to check it by mysql_real_escape_string for security reasons, but we can't use mysql_real_escape_string in ZEND. Then we have to check it by ZEND, we use quote() instead of mysql_real_escape_string .

//get the search_term what user is looking for:
 $search_term=$this->parameters['search_term'];

//mysql_real_escape_string:
$search_term= $this->db->quote($search_term);
$search_term = substr($search_term, 1, strlen($search_term)-2); //Remove quotation from it.

$query = $this->db->select();
$query->from('products', ['product_id', 'product_name', 'product_sub_name']);
$query->where('product_name LIKE ?', '%'.$search_term.'%');
$query->group('product_name');
$query.="
   ORDER BY CASE WHEN product_name like '$search_term %' THEN 0
        WHEN product_name like '$search_term%' THEN 1
        WHEN product_name like '% $search_term%' THEN 2
        ELSE 3
        END, product_name";

return $this->db->fetchAll($query);

This will return what you need, and sort by relevant according to the above SQL query that I found here

If you are going to limit your search, you can easily add it to the $query variable. Then you will have (For example limit it to 10 results):

$query.="
   ORDER BY CASE WHEN product_name like '$search_term %' THEN 0
      WHEN product_name like '$search_term%' THEN 1
      WHEN product_name like '% $search_term%' THEN 2
      ELSE 3
      END, product_name
      LIMIT 0 , 10";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM