ZEND和MySQL - 如何搜索和排序(排序)相关性?

时间:2016-02-24 09:27:16

标签: php mysql search zend-framework

我打算在products表上进行简单搜索,当用户搜索某些内容时,我会使用 product_name LIKE %search_term% 来搜索product表。但我需要按相关性对它们进行排序。

我正在使用ZEND freamwork,我的数据库是MySQL

1 个答案:

答案 0 :(得分:0)

Here有人询问MySQL中的如何按相关性排序,有人提出了一个很好的查询,你需要做的是:

 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

您将从用户那里获得 search_term ,并且出于安全原因必须由mysql_real_escape_string进行检查,但我们无法在ZEND中使用mysql_real_escape_string。然后我们必须通过ZEND进行检查,我们使用 quote() 而不是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);

这将返回您需要的内容,并根据我找到的here

上面的SQL查询按相关性排序

如果您要限制搜索,可以轻松将其添加到$query变量中。然后你将拥有(例如将其限制为10个结果):

$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";