php / mysql搜索查询字符串

时间:2010-10-26 20:21:47

标签: php mysql

我正在尝试搜索可能有或没有空格的术语......例如:iPod Black 30.结果将是除“ipod black used 30”和“used”之外的所有内容。所以基本上它找到所有完整的匹配术语个别匹配术语,并跳过任何可能匹配但在其中有不匹配词的条目,当然还有没有匹配的条目。

table:
prod
-- ipod black 30
-- ipod 30
-- ipod black used 30

types
-- ipod
-- 30
-- black
-- used

2 个答案:

答案 0 :(得分:3)

将搜索词分成单个字符串。然后使用查询中的各个字符串在表中进行精确匹配。

示例代码:

$terms = array();
$terms = explode(" ",$searchstr);

$sql = "select fields from tables where";

$first = true;

foreach($terms as $term)
{

  if(!$first) $sql .= " OR "

  $sql .= "fieldA like ('%".trim($term)."%')";

  $first = false;

}

// execute query!

答案 1 :(得分:1)

你能创建新表吗?例如,您可以创建一个“terms”表,该表与prod和types表有很多对多关系。然后,你可以像这样实现这个逻辑:

-- get the set of all products which contain your terms
select p.id from prod p
inner join prod_terms pt on (p.id = pt.prod_id)
inner join terms t on (pt.term_id = t.id)
where t.term IN (<dynamically built list of terms>)
-- exclude products which contain terms not in your query
and not exists (
    select pt.id from prod_terms pt2
    inner join terms t2 on (pt.term_id = t.id)
    where t2.term NOT IN (<dynamically built list of terms>)
) other_terms

然后你可以为类型表做类似的事情。

警告:

  • 我对SQL Server比较熟悉, 语法可能需要调整 MySQL
  • 查询说明了 一般的想法,但可能导致缓慢 查询计划,所以一定要做perf 调谐
相关问题