我正在处理内部搜索引擎(MySQL数据库)的SQL请求。我想允许用户搜索确切的表达式,因此当他们搜索"foo bar"
时,他们会获得包含foo
和bar
的文档,而不只是foo
或{{1} }。
bar
表:
search_documents_words
| word_id | doc_id | word |
---------------------------
| 1 | 1 | foo |
| 2 | 1 | bar |
| 3 | 2 | foo |
表:
search_documents
我想得到什么:
| doc_id | doc_name |
---------------------
| 1 | mydoc1 |
| 2 | mydoc2 |
假设我在PHP数组中有我的关键字。
我怎样才能做到这一点?
答案 0 :(得分:1)
假设您的搜索关键字在数组中
$search = array('foo','bar');
$keywords = '';
foreach($search as $values) {
$keywords .= "'.$values.',";
}
$keywords = rtrim($keywords,","); // creating words as 'foo','bar'
然后执行此查询
$query = "SELECT B.*
FROM search_documents_words A
JOIN search_documents B ON A.doc_id = B.doc_id
WHERE A.word IN(".$keywords.")";
<强> EDITED 强>
如果相同的文档ID不重复单词,则此案例将有效(带有许多foo条目的文档1将无法使用此查询)
$query = "SELECT B.*
FROM search_documents_words A
JOIN search_documents B ON A.doc_id = B.doc_id
WHERE A.word IN(".$keywords.")
GROUP BY A.doc_id HAVING COUNT(A.doc_id) = '".count($search)."' ";
答案 1 :(得分:1)
子查询可以像这样构建:
$keywords = array('foo','bar');
foreach($keywords as $key)
{
$conditions[] = "word='".$key."'";
}
$condition = implode(" AND ",$conditions);
然后执行此sql查询:
$query = "SELECT *
FROM search_documents
WHERE doc_id
IN (SELECT doc_id
FROM search_documents_words
WHERE ".$condition.")"
希望这会有所帮助!!
答案 2 :(得分:0)
您可以使用GROUP_CONCAT和HAVING子句
SELECT sd.doc_id,
sd.doc_name,
GROUP_CONCAT(sdw.word Order by sdw.word SEPARATOR ' ') AS sdwWord
FROM search_documents sd
JOIN search_documents_words sdw ON sd.doc_id = sdw.doc_id
GROUP BY sd.doc_id, sd.doc_name
HAVING sdwWord = <search expression>