doubingjiu3199 2016-02-24 09:27
浏览 43
已采纳

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

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

  • 写回答

1条回答 默认 最新

  • dongmei1828 2016-02-24 09:27
    关注

    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";
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大