【问题标题】:How to count the number of matches when executing query SELECT WHERE LIKE?执行查询SELECT WHERE LIKE时如何计算匹配数?
【发布时间】:2014-01-23 20:44:03
【问题描述】:

执行如下查询时如何计算匹配数:

编辑:对不起,我认为你们会理解的不好的解释。 这是更新。

$thingsilike = explode(" ", $search); 
foreach($thingsilike as $things){
$array[] = "keywords LIKE '%$things%'";
}

让我们说下面的句子“我喜欢苹果和橘子”被放入数组中。数组看起来像这样

$array('I', 'like', 'apples', 'and', 'oranges');

query = ("SELECT * FROM row WHERE thingspeoplelike LIKE .implode(' OR', $array);

然后查询将搜索“thingspeoplelike”中的每个关键字 我想知道的是如何找出与单词有多少匹配 所以让我们说在thingpeoplelike中有三个句子:

第一个“我喜欢苹果和橘子” 匹配的数量将是 5

第二个“我喜欢苹果和菠萝” 匹配数量为 4

第三句“我喜欢苹果” 匹配数量为 3

我想知道如何再次找出并计算匹配的数量,抱歉解释不好,提前谢谢大家!

【问题讨论】:

  • 发布更多 PHP 代码 - 这就是 rowCount 的用途:php.net/manual/en/pdostatement.rowcount.php
  • implode(' OR',$array) 是什么意思,你到底想做什么?
  • user3188287 想要将 $array 的元素与 ' OR ' 作为分隔符组合起来用作 LIKE 子句
  • @scrowler 很抱歉发布了更多代码和更好的解释。
  • 同意。这绝对是完全不同的东西。不确定你是否可以用更少的努力做到这一点。像 solr 这样的倒排搜索索引可能是实现您目标的更好选择。

标签: php mysql


【解决方案1】:

如果您想计算与您的查询匹配的行数,或者更确切地说是您的数组的输入,那么只需使用:

"SELECT COUNT(*) FROM row WHERE things LIKE ".implode(' OR ', $array)

问题澄清后更新:

/* split the input sentence */
$thingsilike = explode(" ", $search);

$result = /* Get all sentences (thingspeoplelike) from row and store it in $result */

foreach($result as $sentence) {

    $count = 0;
    $parts = explode(" ", $sentence);

    foreach($thingsilike as $keyword) {

        if(in_array($keyword, $parts) == true) {

            $count = $count + 1;
        }
    }

    echo "Found {$count} matches for result '{$sentence}'";
}

我希望这就是你所寻找的......

【讨论】:

  • 这个解决方案有什么问题?如果还有其他目标,则必须更准确地定义问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多