Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/245.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 在mysql中搜索字符串数组_Php_Mysql_Arrays - Fatal编程技术网

Php 在mysql中搜索字符串数组

Php 在mysql中搜索字符串数组,php,mysql,arrays,Php,Mysql,Arrays,我有一个字符串数组,我需要搜索该数组的字符串是否存在于数据库中。我使用以下查询: foreach($array as $s) { if(preg_match('/^(\bpho)\w+\b$/', $s)) { $query="select * from dictionary where words REGEXP '^".$s."$'"; $result=$db->query($query) or die($db->error); if($result

我有一个字符串数组,我需要搜索该数组的字符串是否存在于数据库中。我使用以下查询:

foreach($array as $s)
{   
if(preg_match('/^(\bpho)\w+\b$/', $s))
{ 
    $query="select * from dictionary where words REGEXP '^".$s."$'";
    $result=$db->query($query) or die($db->error);
    if($result)
    {
    $count += $result->num_rows;
    }
}
}

但是这个查询需要很长时间才能执行。请提供一个减少搜索时间的解决方案

我不认为您的问题与代码有关。我认为你应该优化你的数据库。
我不是很擅长,但我认为您可以在数据库中添加索引以加快研究

使用交替将所有搜索字符串合并到单个正则表达式中

$searches = array();
foreach ($array as $s) {
    if (preg_match('/^(\bpho)\w+\b$/', $s)) {
        $searches[] = "($s)";
    }
}
$regexp = '^(' . implode('|', $searches) . ')$';
$query="select 1 from dictionary where words REGEXP '$regexp'";
$result=$db->query($query) or die($db->error);
$count = $result->num_rows;
如果
$array
不包含正则表达式,则不需要使用SQL
REGEXP
运算符。您可以在中使用

$searches = array();
foreach ($array as $s) {
    if (preg_match('/^(\bpho)\w+\b$/', $s)) {
        $searches[] = "'$s'";
    }
}
$in_list = implode(',', $searches);
$query="select 1 from dictionary where words IN ($in_list)";
$result=$db->query($query) or die($db->error);
$count = $result->num_rows;

搜索整个数据库是一项庞大的工作,我认为更好的方法是缓存数据库的某些部分,而不是在缓存中搜索。Redis非常好

  • 修改查询,使其不会选择所有表列—这是一种资源浪费。相反,只需让数据库计算包含搜索查询的行数,并仅返回一个答案(匹配项):
  • $query=“从字典中选择COUNT(id)作为匹配项,其中单词REGEXP'^”。$s.“$”

  • 您如何为数据库编制索引?如果您的words列没有正确索引,那么您的regexp将花费很长时间。检查您的数据库结构,并可能向words列添加索引

  • 请注意,不要忘记获取匹配项列,而不是使用num_rows

    如果您可以将搜索范围缩小到特定的表或列,那么您可以在该特定列上使用索引。当看起来您正在进行精确匹配时,您为什么使用
    REGEXP
    $array
    是否包含正则表达式?是的,您可以看到我正在搜索以“pho”开头的所有元素。
    $array
    是否包含类似于
    pho\d*
    的内容,即
    $array
    中是否存在正则表达式运算符?或者它们只是像
    拼音
    ?我理解你为什么使用
    preg_match
    ,我的问题是为什么你使用
    而单词REGEXP
    。索引优化REGEXP匹配的能力有限。而这正是他所需要的。也许你应该更具体一些。你推荐哪种类型的优化使正则表达式匹配更快?你称之为“更具体”?