正如我们所知,MySQL可以通过LIKE和LIMIT获得结果,但我的问题是如何逐个搜索数据库中的某些单词并显示结果而不重复?
我的意思是例如当用户搜索“用于php和mysql的书”时,我们在For循环中发送查询,通过以下方式将单词发送到DB:
SELECT * FROM table WHERE title LIKE %i% LIMIT 5
但是这段代码只显示重复的结果,实际上每个单词显示5个结果然后另一个单词另外5个结果和...我需要逐个搜索db的单词,但最后只显示5个匹配结果复制!抱歉我的英语不好:)
答案 0 :(得分:2)
我一直在阅读评论和你的问题,我认为你需要一些PHP来准备你的MySql语句,以及一个Mysql查询来获取匹配的结果仅限于前5个没有重复的项目?
如果是这样!!
<强> PHP 强>
<?php
$searchFieldData = $_POST['search'];
$searchArr = explode(" ", $searchFieldData);
$sqlWhere = '';
$count = count($searchArr);
foreach ($searchArr as $or) {
$sqlWhere.= " title LIKE '%".$or."%' ";
if ($count>1) $sqlWhere.= " OR ";
$count--;
}
$query = "SELECT col1, col2, ... FROM table WHERE ".$sqlWhere." LIMIT 5";
?>
以上代码会返回搜索字词:“超级超级查询抓取工具”
SELECT col1,col2,... FROM table WHERE title LIKE'%super%'OR title LIKE'%hyper%'OR title LIKE'%query%'OR title LIKE'%crawler%'LIMIT 5
现在为MYSQL MAGIC
如果您不想要任何重复结果,只需使用: GROUP BY'title'
,您的最终查询将是:
$query = "SELECT col1, col2, ... FROM table WHERE ".$sqlWhere." GROUP BY 'title' LIMIT 5";
答案 1 :(得分:1)
我想你想要这样的东西:
SELECT col1, col2, ...
FROM table
WHERE title LIKE '%a%' OR title LIKE '%b%' OR title LIKE '%c%'
LIMIT 5
注意:
LIKE '%xxx%'
的速度很慢。请考虑使用索引全文搜索。答案 2 :(得分:1)
您是否只想通过MySQL实现这一目标?我用 PHP :
显示一个$result = array();
$excludeIds = array(); //store recored id already got
$words = explode(" ", $_POST['input']);
foreach($words as $word) {
//if there is no 'id' column, use another one instead
$condForNoDup = ($excludeIds) ?
"AND id NOT IN (".implode(',', $excludeIds).")" : "";
$word = '%'.mysql_real_escape_string($word).'%';
$sql = "SELECT * FROM table
WHERE title LIKE '{$word}' {$condForNoDup}
LIMIT 5";
//executeQuery() returns array which has 'id' as key
if($_result = executeQuery($sql)) {
$excludeIds = array_merge($excludeIds, array_keys($result));
$result = array_merge($result, $_result);
}
}
print_r($result);
尴尬......我也想知道只有MySQL的智能答案:)