【问题标题】:sql select query multiple incomplete wordssql select查询多个不完整的单词
【发布时间】:2012-03-26 20:13:15
【问题描述】:

我的问题需要帮助...

我的数据库中有一条记录,其中 1 行包含多个单词。

示例:

产品名称:

white sugar big
brown sugar big
white sugar small
brown sugar small

现在...我做了一个选择查询,即使不完整的单词也能选择产品。我在这里使用“喜欢”。

select * from products where prod_name like '%".$pname."%' 

注意:$pname 是一个 php 变量...

所以我尝试查询“whi”这个词

那么结果是:

white sugar big
white sugar small

现在我的问题是我想让我的搜索灵活,如果我搜索“whi bi”这个词

结果将是“

white sugar big....

thnx 提前 =)

【问题讨论】:

    标签: php mysql sql select


    【解决方案1】:

    在构建查询之前,只需将 php 变量中的每个空格替换为 %。

    【讨论】:

      【解决方案2】:

      将搜索词中的空格替换为% like $term = str_replace(" ", "%", $term) 然后进行数据库查询。

      【讨论】:

        【解决方案3】:

        您可能想尝试在 MYSQL 中进行全文搜索,它会自动编译基于评分的搜索:

        见http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html

        select * from products where  MATCH (prod_name) AGAINST ('whi bi')
        

        或者,您可以分解单词并构建多个搜索:

        $searchTerms = explode(' ',$pname);
        $term='%'.str_replace(' ','%',$pname).'%';
        $sql = "select * from products where prod_name like '$term'";
        

        【讨论】:

          【解决方案4】:

          简单的答案类似于使用带有LIKE 关键字的“%xx%yyy%zzz%”发布的答案。如果您希望进行复杂的搜索,那么您可以使用 REGEXP:

          select * from products where prod_name REGEXP 'whi[.]*bi[.]*'
          

          那么你的PHP代码就需要准备了:

          $keywords = "whi bi"; // whatever terms
          $search = str_replace(' ','[.]*',$keywords)."[.]*";
          $sql = "select * from products where prod_name REGEXP '".$search."'";
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2018-09-25
            • 1970-01-01
            • 2017-01-08
            • 2014-11-02
            • 1970-01-01
            • 2019-04-11
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多