php - 在多个字段中查找多个字符串

标签 php mysql

我试图通过在多个字段中搜索多个术语来从 MySQL 数据库获取结果。下面的脚本可以工作,但不太符合我需要的方式,而且我很难找到实现它的方法。

目前,如果我搜索“苹果桃子”,它将返回任何字段中包含“苹果”“桃子”的所有结果。 IE。如果一条记录有“苹果”但没有“桃子”,它将产生一个结果。

按照预期的行为,只有在给定记录中找到任何字段上的所有搜索词时,我才应该得到结果。 IE。 “苹果”可以在字段 f1 上找到,“桃子”可以在字段 f2 上找到。如果只找到“苹果”,那么它不是结果。

<?php
if (!isset($_REQUEST['term'])) exit;
$dblink = mysql_connect('localhost', 'root', 'pass') or die(mysql_error());
mysql_select_db('mytable');
mysql_set_charset('utf8', $dblink);
// query the database table for strings that match 'term'
$lcSearchVal = mysql_real_escape_string($_REQUEST['term']);
$lcSearchVal = explode(' ', $lcSearchVal);
$sql = 'SELECT id, f1, f2, f3, f4 FROM mytable 
        WHERE (';
$parts = array();
foreach($lcSearchVal as $lcSearchWord) {
    if ($lcSearchWord <> "") {
        $parts[] = '`id` LIKE "%' . $lcSearchWord . '%"';
    }
    if ($lcSearchWord <> "") {
        $parts[] = '`f1` LIKE "%' . $lcSearchWord . '%"';
    }
    if ($lcSearchWord <> "") {
        $parts[] = '`f2` LIKE "%' . $lcSearchWord . '%"';
    }
    if ($lcSearchWord <> "") {
        $parts[] = '`f3` LIKE "%' . $lcSearchWord . '%"';
    }
    if ($lcSearchWord <> "") {
        $parts[] = '`f4` LIKE "%' . $lcSearchWord . '%"';
    }
}
$sql.= implode(' OR ', $parts) . ') order BY id desc limit 0,10';
$rs = mysql_query($sql, $dblink);
// loop through each string returned and format the response for jQuery
$data = array();
$data[] = array('value' => "", 'label' => " >> Last 10 results:", 'desc' => "");
if ($rs && mysql_num_rows($rs)) {
    while ($row = mysql_fetch_array($rs, MYSQL_ASSOC)) {
        if (strlen($row['f3']) > 250) {
            $row['f3'] = substr($row['f3'], 0, 250) . " [...]";
        }
        $data[] = array('value' => $row['id'], 'label' => $row['id'] . '/' . $row['f1'] . ' (' . $row['f2'] . ') ' . $row['f4'], 'desc' => $row['f3']);
    }
}
// jQuery wants JSON data
echo json_encode($data);
flush();
?>

感谢您的参与

最佳答案

考虑进行全文索引和查询:

http://www.devarticles.com/c/a/MySQL/Getting-Started-With-MySQLs-Full-Text-Search-Capabilities/

比使用类似的语句来处理这类事情要好得多。

关于php - 在多个字段中查找多个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12206421/

相关文章:

php - 在 phpunit laravel-4 中使用 json POST 测试特定元素

mysql - 使用 Spring Data 传播外键

php - 使用xampp的php mysql连接出错

php - 没有从数据库中获取所有行

php - Zend Framework 如何获取循环中的项目数?部分循环部分计数器和?

php - 无法在 centOS 上安装 php-mbstring

php - Codeigniter:您必须使用 "set"方法来更新条目

php - 根据 mysql sql 查询中的投票类型对总和进行加减

sql - 在 MySQL 中检索日期格式行

最佳匹配的MySQL搜索算法