dsc71976 2012-04-27 18:49
浏览 77
已采纳

使用LIKE和LIMIT逐个查询字符串单词的结果

as we know it, MySQL can get results by LIKE and LIMIT, but my problem is how we can search DB for some words of a string one by one and show result without duplication?

my means is for example when user make search for "a book for php and mysql" we send query in For loop, word to word to DB by:

SELECT * FROM table WHERE title LIKE %i% LIMIT 5

but this code just show duplicated result, indeed for each word it shows 5 results then for another word another 5 result and... i need to search db for words one by one, but at last show just 5 match results without duplication! sorry for my poor english:)

  • 写回答

3条回答 默认 最新

  • douju1280 2012-04-27 19:37
    关注

    I've been reading the comments and your question, and I think that you need a bit of PHP to prepare your MySql statement, and a Mysql Query to fetch matching results limited to the first 5 without repeated items?

    If so!!

    PHP

    <?php
      $searchFieldData = $_POST['search'];
      $searchArr = explode(" ", $searchFieldData);
    
      $sqlWhere = '';
      $count = count($searchArr);
      foreach ($searchArr as $or) {
        $sqlWhere.= " title LIKE '%".$or."%' ";
        if ($count>1) $sqlWhere.= " OR ";
        $count--;
      }
    
      $query = "SELECT col1, col2, ... FROM table WHERE ".$sqlWhere." LIMIT 5";
    ?>
    

    The above code would return for the search term: "super hyper query crawler"

    SELECT col1, col2, ... FROM table WHERE title LIKE '%super%' OR title LIKE '%hyper%' OR title LIKE '%query%' OR title LIKE '%crawler%' LIMIT 5


    NOW FOR THE MYSQL MAGIC

    If you don't want any repeated results, just use: GROUP BY 'title'

    and your final query would be:

    $query = "SELECT col1, col2, ... FROM table WHERE ".$sqlWhere." GROUP BY 'title' LIMIT 5";
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 Stata 面板数据模型选择
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用