【问题标题】:fetching records with same random word in specified column in mysql在mysql的指定列中获取具有相同随机单词的记录
【发布时间】:2015-12-15 02:33:20
【问题描述】:

我在表中有以下数据,

id               Description              Category
1      I  am Desc with printer            main category
2      I am desc with test                 test category  
3          new printer desc                third category  
4        new test category                  printer category

等等……

我想在他们的描述字段中找到具有相同单词的计数(可以是打印机,但不是预定义的)。 对于前输出应该是:

Total      Word which is same
  2         printer
  2          test

我尝试使用带有布尔选项的 http://dev.mysql.com/doc/refman/5.7/en/fulltext-boolean.html 示例,但它没有提供所需的输出。

我给出的例子是打印机,它可以是任何东西。 我不想在任何地方的查询中指定这个词,因为它可以是任何东西。 只有在任何地方都有相同单词的描述才能输出。

提前致谢。

【问题讨论】:

    标签: php mysql


    【解决方案1】:

    试试这个:

    SELECT SUM(IF(Description like '%printer%',1,0)) AS Printer,SUM(IF(Description like '%test%',1,0)) AS Test FROM `yourTable`
    

    这可能会有所帮助:)

    【讨论】:

      【解决方案2】:

      构建描述中所有单词的字典

      $dbh = new PDO($dsn, $user, $password);
      
      $sql = "SELECT description FROM tableName";
      
      foreach($dbh->query($sql, PDO::FETCH_ASSOC) as $result){
          foreach (explode(' ',$result['description']) as $word){
              $words[] = $word;
          }   
      }
      

      使用array_count_values计算数组中的重复值,可选择降序排序

      $wordCount = array_count_values($words);
      arsort($wordCount);
      

      然后使用array_filter过滤数组以消除只出现一次的单词

      $filteredWordCount = array_filter($wordCount, function($value){
          return $value!=1;
      });
      

      这应该给你一个数组,其中单词本身作为索引,出现次数作为值。

      遍历数组并运行 COUNT 查询

      foreach($filteredWordCount as $word=>$value){
          $countSQL = 'select COUNT(*) as rowCount from tableName where description like "%' . $word . '%" ';
          $res = $dbh->query($countSQL, PDO::FETCH_ASSOC);
      
          $count[$word] = $res->fetch()['rowCount'];
      }
      

      像以前一样根据值对数组进行排序,然后打印出来

      arsort($count);
      print_r($count);
      

      如果您需要关于行数的条件,例如,仅返回出现在超过 5 条记录中的单词,您可以像这样调整查询

      foreach($filteredWordCount as $word=>$value){
          $countSQL = 'select COUNT(*) as rowCount from domains where description like "%' . $word . '%" HAVING rowCount > 5';
          $res = $dbh->query($countSQL, PDO::FETCH_ASSOC);
      
          $c = $res->fetch()['rowCount'];
      
          if (isset($c)){
              $count[$word] = $c;
          }
      }
      

      【讨论】:

      • 这很容易被SQL注入,它应该使用参数化查询。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-05
      • 1970-01-01
      • 1970-01-01
      • 2015-10-06
      • 2011-05-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多